Bubble sort is one of the simplest sorting algorithms.
It is a comparison-based sorting algorithm.
In this sorting algorithm, each pair of adjacent elements is compared and swapped if they are not in order.
Disadvantage:-
Not suitable for large data sets.
Average and worst-case complexity = O(n^2)
Normal code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class BubbleSort{ public static void main(String[] args){ int[] arr = {3, 2, 5, 4, 7, 9, 1}; for(int i=0; i<arr.length-1; i++){ for(int j=0; j<arr.length-1-i; j++){ if(arr[j]>arr[j+1]){ int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } for(int x:arr) System.out.print(x+" "); } } |
Optimize Code:-
public class BubbleSort{ public static void main(String []args){ int[] arr = {3,2,5,4,7,9,1}; for(int i=0; i<=arr.length-2; i++){ boolean flag = false; for(int j=0; j<=arr.length-i-2; j++){ if(arr[j]>arr[j+1]){ int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; flag = true; } } if(flag==false) break; } for(int i:arr) System.out.print(i+" "); } } |