Bubble Sort
  • Best Case, O(n)
  • Worst Case, Ω(n^2)
  • Memory Complexity, O(1)
  • import java.util.Random;
    import java.util.Arrays;
    
    public class Bubble
    {
        //bubble sort	
        public static void bubbleSort(int arr[])
        {
            int n = arr.length;
            for (int i = 0; i < n-1; i++)
                for (int j = 0; j < n-i-1; j++)
                    if (arr[j] > arr[j+1])
                    {
                        // swap arr[j] and arr[j+1]
                        int temp = arr[j];
                        arr[j] = arr[j+1];
                        arr[j+1] = temp;
                    }
        }
    
        //generate an array with random elements
        public static int [] getArray(int size)
        {
    	    int [] array = new int[size];
    	    Random r = new Random();
    
    	    for(int i = 0; i < size; i++)
    		    array[i] = r.nextInt(100);
    
    	    return array;
        }
    
        //display an array
        public static void displayArray(int arr[])
        {
    	    for(int e : arr)
    		    System.out.printf("%5d", e);
    	    System.out.println();
        }
    
        public static void main(String args[])
        {
    	    long start, end;
    	    int [] array;
    	    int [] array2;
    	    int size = 100000;
    
    	    //create two same arrays
    	    array = getArray(size);
    	    array2 = Arrays.copyOf(array, array.length);
    
    	    //sort a huge array with bubble sort
    	    start = System.currentTimeMillis();
    	    bubbleSort(array);
    	    end = System.currentTimeMillis();
    	    System.out.printf("Bubble sort time: %10f%n", (end-start)/1000000.0);
    
    	    //sort the array with build-in sort function in Arrays class
    	    start = System.currentTimeMillis();
    	    Arrays.sort(array2);
    	    end = System.currentTimeMillis();
    	    System.out.printf("Build-in sort time: %10f%n", (end-start)/1000000.0);
    
    	    //validate bubble sort
    	    if(Arrays.equals(array, array2))
    		    System.out.println("Bubble sort is validated ...");
    	    else
    		    System.out.println("Bubble sort does not work correctly ...");
        }
    }
    			
    Reach Best Case with Control
    public void bubbleSort(int arr[]) {
        boolean swapped = true;
        for(int i = 0, len = arr.length; swapped && i < len - 1; i++) {
            swapped = false;
            for(int j = 0; j < len - i - 1; j++) {
                if(arr[j + 1] < arr[j]) {
                    swap(arr, j, j + 1);
                    swapped = true;
                }
            }
        }
    }
    			
    Reference