Intro to the Bubble Sort Algorithm

  • The Bubble Sort algorithm will:

    • Compare every pair of adjacent elements

    • Exchange (= swap) them if they are out of order

  • Example:

           2  9  5  4  8  1        2 < 9 OK
    
    
    
    
    
    
    
    
    
    
    
    

Intro to the Bubble Sort Algorithm

  • The Bubble Sort algorithm will:

    • Compare every pair of adjacent elements

    • Exchange (= swap) them if they are out of order

  • Example:

           2  9  5  4  8  1             
           2  9  5  4  8  1        9 > 5  Swap
    
    
    
    
    
    
    
    
    
    
    

Intro to the Bubble Sort Algorithm

  • The Bubble Sort algorithm will:

    • Compare every pair of adjacent elements

    • Exchange (= swap) them if they are out of order

  • Example:

           2  9  5  4  8  1             
           2  9  5  4  8  1       
           2  5  9  4  8  1        9 > 4  Swap
    
    
    
    
    
    
    
    
    
    

Intro to the Bubble Sort Algorithm

  • The Bubble Sort algorithm will:

    • Compare every pair of adjacent elements

    • Exchange (= swap) them if they are out of order

  • Example:

           2  9  5  4  8  1             
           2  9  5  4  8  1 
           2  5  9  4  8  1      
           2  5  4  9  8  1        9 > 8  Swap
    
    
    
    
    
    
    
    
    

Intro to the Bubble Sort Algorithm

  • The Bubble Sort algorithm will:

    • Compare every pair of adjacent elements

    • Exchange (= swap) them if they are out of order

  • Example:

           2  9  5  4  8  1             
           2  9  5  4  8  1 
           2  5  9  4  8  1      
           2  5  4  9  8  1   
           2  5  4  8  9  1        9 > 1  Swap
    
    
    
    
    
    
    
    

Intro to the Bubble Sort Algorithm

  • The Bubble Sort algorithm will:

    • Compare every pair of adjacent elements

    • Exchange (= swap) them if they are out of order

  • Example:

           2  9  5  4  8  1             
           2  9  5  4  8  1 
           2  5  9  4  8  1      
           2  5  4  9  8  1   
           2  5  4  8  9  1     
           2  5  4  8  1  9        Finish 1 iteration
    
    
    
    
    
    
    

Intro to the Bubble Sort Algorithm

  • The Bubble Sort algorithm will:

    • Compare every pair of adjacent elements

    • Exchange (= swap) them if they are out of order

  • Example:

           2  9  5  4  8  1             
           2  9  5  4  8  1 
           2  5  9  4  8  1      
           2  5  4  9  8  1   
           2  5  4  8  9  1     
           2  5  4  8  1  9       
    
     Notice after 1 iteration:
    
         the largest element is in the correct position
    
     Therefore: if we repeat n-1 times, the array will be sorted
    

Intro to the Bubble Sort Algorithm

  • The Bubble Sort algorithm will:

    • Compare every pair of adjacent elements

    • Exchange (= swap) them if they are out of order

  • Example: the complete execution of the Bubble Sort algorithm


  • Liang has a animation of the Bubble Sort algorithm:

The Bubble Sort Algorithm

We start writing the header of the BubbleSort( ) algorithm as a generic method:

    public static <T extends Comparable<T>> void sort( T[] arr )
    {
        int n = arr.length;

        for (int i = 0; i < n-1; i++)          // Repeat n-1 times
        {
	   // Compare every adjacent pair of element
           for ( int j = 0; j < n-1-i; j++ )
	   {
               if ( arr[j].compareTo(arr[j+1]) > 0 ) // If out of place
                   exch( arr, j, j+1);  // Swap list[j] and list[j+1]
           }
        }
    }

The Bubble Sort Algorithm

Repeat the steps n−1 times:

    public static <T extends Comparable<T>> void sort( T[] arr )
    {
        int n = arr.length;

        for (int i = 0; i < n-1; i++)          // Repeat n-1 times
        {
	   // Compare every adjacent pair of element
           for ( int j = 0; j < n-1-i; j++ )
	   {
               if ( arr[j].compareTo(arr[j+1]) > 0 ) // If out of place
                   exch( arr, j, j+1);  // Swap list[j] and list[j+1]
           }
        }
    }

The Bubble Sort Algorithm

In each iteration:   compare every pair of adjacent element

    public static <T extends Comparable<T>> void sort( T[] arr )
    {
        int n = arr.length;

        for (int i = 0; i < n-1; i++)          // Repeat n-1 times
        {
	   // Compare every adjacent pair of element
           for ( int j = 0; j < n-1-i; j++ )
	   {
               if ( arr[j].compareTo(arr[j+1]) > 0 ) // If out of place
                   exch( arr, j, j+1);  // Swap list[j] and list[j+1]  
           }
        }
    }

The Bubble Sort Algorithm

If an pair is out of place, swap them:

    public static <T extends Comparable<T>> void sort( T[] arr )
    {
        int n = arr.length;

        for (int i = 0; i < n-1; i++)          // Repeat n-1 times
        {
	   // Compare every adjacent pair of element
           for ( int j = 0; j < n-1-i; j++ )
	   {
               if ( arr[j].compareTo(arr[j+1]) > 0 ) // If out of place
                   exch( arr, j, j+1);  // Swap arr[j] and arr[j+1]  
           }
        }
    }

DEMO: demo/14-sort/03-bubble-sort/BubbleSort.java + Demo.java (Integer) + Demo2.java (String)

Runtime analysis of the Bubble Sort

  • The loop structure of the Bubble Sort algorithm (assuming array length = n):

      for (int i = 0; i < n-1; i++)
         for ( int j = 0; j < n-1-i; j++ )
             doPrimitive();
    

    Analysis:

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

Runtime analysis of the Bubble Sort

  • The loop structure of the Bubble Sort algorithm (assuming array length = n):

      for (int i = 0; i < n-1; i++)
         for ( int j = 0; j < n-1-i; j++ )
             doPrimitive();
    

    Analysis:

     The variable i takes on these values:
    
        i =    0    1    2    3     ....   n-2
    
    
    
    
    
    
    
    
    
    
    
    
    

Runtime analysis of the Bubble Sort

  • The loop structure of the Bubble Sort algorithm (assuming array length = n):

      for (int i = 0; i < n-1; i++)
         for ( int j = 0; j < n-1-i; j++ )
             doPrimitive();
    

    Analysis:

     The variable j takes on these values for each i:
    
        i =    0    1    2    3     ....   n-2   
            ----------------------------------- 
        j =    0    0    0    0             0
               1    1    1
    	   2    2   ...
    	  ...  ...  n-4
    	  ...  n-3
    	  n-2
    
    
    
    
    
    

Runtime analysis of the Bubble Sort

  • The loop structure of the Bubble Sort algorithm (assuming array length = n):

      for (int i = 0; i < n-1; i++)
         for ( int j = 0; j < n-1-i; j++ )
             doPrimitive();
    

    Analysis:

     The variable j takes on these values for each i:
    
        i =    0    1    2    3     ....   n-2   
            ----------------------------------- 
        j =    0    0    0    0             0
               1    1    1
    	   2    2   ...
    	  ...  ...  n-4
    	  ...  n-3
    	  n-2
    
     #Iterations = (n-1) + (n-2) + (n-3) + .... + 2 + 1  (Triangular sum !)
    
    
    
    

Runtime analysis of the Bubble Sort

  • The loop structure of the Bubble Sort algorithm (assuming array length = n):

      for (int i = 0; i < n-1; i++)
         for ( int j = 0; j < n-1-i; j++ )
             doPrimitive();
    

    Analysis:

     The variable j takes on these values for each i:
    
        i =    0    1    2    3     ....   n-2   
            ----------------------------------- 
        j =    0    0    0    0             0
               1    1    1
    	   2    2   ...
    	  ...  ...  n-4
    	  ...  n-3
    	  n-2
    
     #Iterations = (n-1) + (n-2) + (n-3) + .... + 2 + 1  (Triangular sum !)
                 = (n-1)n/2
    
     Runtime = O(n2)         (same as Selection Sort...)
    

Improving the basic Bubble Sort Algorithm

  • Facts:

    1. In each iteration, the Bubble Sort algorithm will compare every pair of elements and swap only out-of-place pairs

    2. When the array is sorted:

      • An (entire) iteration in Bubble Sort will not perform any exchange operation

  • Example: if the array was:

        1   2    3    4    5    6    7
    

    There will be no out-of-order pairs

    Consequently:

    • No swap operations will be performed

The improved Bubble Sort Algorithm

Here is the baisc Bubble Sort algorithm (with spaces added so I can insert the improvement):

    public static <T extends Comparable<T>> void sort( T[] arr )
    {
        int n = arr.length;


        for (int i = 0; i < n-1; i++)          // Repeat n-1 times
        {


	   // Compare every adjacent pair of element
           for ( int j = 0; j < n-1-i; j++ )
	   {
               if ( arr[j].compareTo(arr[j+1]) > 0 ) // If out of place

                   exch( arr, j, j+1);  // Swap arr[j] and arr[j+1]  


           }



        }
    }

 

The improved Bubble Sort Algorithm

We first add a boolean variable to detect whether an iteration has perform at least 1 exch( ) operation:

    public static <T extends Comparable<T>> void sort( T[] arr )
    {
        int n = arr.length;
	boolean swapped;

        for (int i = 0; i < n-1; i++)          // Repeat n-1 times
        {


	   // Compare every adjacent pair of element
           for ( int j = 0; j < n-1-i; j++ )
	   {
               if ( arr[j].compareTo(arr[j+1]) > 0 ) // If out of place

                   exch( arr, j, j+1);  // Swap arr[j] and arr[j+1]  


           }



        }
    }

 

The improved Bubble Sort Algorithm

When the iteration begins, we set swapped = false:

    public static <T extends Comparable<T>> void sort( T[] arr )
    {
        int n = arr.length;
	boolean swapped;

        for (int i = 0; i < n-1; i++)          // Repeat n-1 times
        {
           swapped = false;

	   // Compare every adjacent pair of element
           for ( int j = 0; j < n-1-i; j++ )
	   {
               if ( arr[j].compareTo(arr[j+1]) > 0 ) // If out of place

                   exch( arr, j, j+1);  // Swap arr[j] and arr[j+1]  


           }



        }
    }

 

The improved Bubble Sort Algorithm

If there is an out-of-place pair, we set swapped = true to indicate that the array is not yet sorted:

    public static <T extends Comparable<T>> void sort( T[] arr )
    {
        int n = arr.length;
	boolean swapped;

        for (int i = 0; i < n-1; i++)          // Repeat n-1 times
        {
           swapped = false;

	   // Compare every adjacent pair of element
           for ( int j = 0; j < n-1-i; j++ )
	   {
               if ( arr[j].compareTo(arr[j+1]) > 0 ) // If out of place
	       {
                   exch( arr, j, j+1);  // Swap arr[j] and arr[j+1]  
		   swapped = true;
	       }
           }



        }
    }

 

The improved Bubble Sort Algorithm

Finally: if at the end of the iteration, swapped == false, we konw that the array is sorted and exit the loop:

    public static <T extends Comparable<T>> void sort( T[] arr )
    {
        int n = arr.length;
	boolean swapped;

        for (int i = 0; i < n-1; i++)          // Repeat n-1 times
        {
           swapped = false;

	   // Compare every adjacent pair of element
           for ( int j = 0; j < n-1-i; j++ )
	   {
               if ( arr[j].compareTo(arr[j+1]) > 0 ) // If out of place
	       {
                   exch( arr, j, j+1);  // Swap arr[j] and arr[j+1]  
		   swapped = true;
	       }
           }

	   if ( swapped == false )  // No swaps --> sorted !!
	       break;     // exit loop
        }
    }

Comment: the "improved" Bubble Sort has the same worst case running time as the basic version....
There are inputs that will make the "improved" Bubble Sort perform n-1 iterations to complete the sorting

Additional properties of Bubble sorting algorithms

  • Recall: In-place

    • A sorting algorithm is in-place if it does not require another array to execute the algorithm

    The Bubble Sort algorithm is an in-place sorting algorithm


  • Recall:   Stable:

    • A sorting algorithm is stable if it preserves the relative order of equal keys in the array

    The Bubble Sort algorithm is stable

    (Because it only swap adjacent elements and will never swap 2 keys that are equal)