Bubble sort sort array checking 2 element in each time, like first time it will check first 2 element like 1,2, then 2,3 so on.
time complexity O(n^2)
public class BubbleSort {
public static void main(String[] args) {
int[] arr = { 2, 4, 23, 54, 67, 23, 66, 35, 28, 9, 65, 876, 32,1,0,2,4,5 };
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(bubbleSort((arr))));
}
private static int[] bubbleSort(int[] arr) {
for(int i=0;i<arr.length;i++) {
int temp;
for(int j=0;j<arr.length-1;j++) {
if(arr[j]>arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
}
time complexity O(n^2)
public class BubbleSort {
public static void main(String[] args) {
int[] arr = { 2, 4, 23, 54, 67, 23, 66, 35, 28, 9, 65, 876, 32,1,0,2,4,5 };
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(bubbleSort((arr))));
}
private static int[] bubbleSort(int[] arr) {
for(int i=0;i<arr.length;i++) {
int temp;
for(int j=0;j<arr.length-1;j++) {
if(arr[j]>arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
}