Here is my code:
import java.util.Scanner;
public class BubbleSort{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int[] array = new int[5];
for(int i = 0; i < array.length; i++){
System.out.println("Enter value: ");
array[i] = sc.nextInt();
}
int temp;
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array.length - 1; j++) {
if(array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = array[j];
}
}
}
System.out.print("Sorted Array: ");
for(int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
}
When I input an array. The output is:
Enter value:
5
Enter value:
4
Enter value:
3
Enter value:
2
Enter value:
1
Sorted Array: 1 1 1 1 1
Your integer swapping logic is incorrect.
replace this line
array[j + 1] = array[j];
with
array[j + 1] = temp;