The Bubble Sort algorithm

• How the algorithm got its name

• The bubble sort algorithm got its name from the way bubbles rises to the surface:

• Notice that:

 The largest bubble will reach the surface first The second largest bubble will reach the surface next And so on.

• In the bubble sort algorithm:

 The largest value will reach its correct position first The second largest bubble will reach its correct position next And so on.

• Description of the bubble sort algorithm

• Main operation performed by the bubble sort algorithm:

 ``` for ( each adjacent pair of items ) { if ( the pair of items are out of order ) swap the pair of items } ```

Example:

Result:

 The largest value will be moved to the last position (= its correct position)

• How to sort all the items:

 The main operation of the bubble sort is repeated until the items are in the correct order

• The bubble sort algorithm: in pseudo code

• The bubble sort algorithm:

 ``` public static void sort( double[] a ) { while ( array a is not sorted ) { for ( each adjacent pair of items ) { if ( the pair of items are out of order ) swap the pair of items } } } ```

• Refined pseudo code:

 ``` public static void sort( double[] a ) { while ( array a not sorted ) { for ( i = 0 ; i < a.length-1 ; i ++ ) { if ( a[i] > a[i+1] ) // Pair out of order { Swap a[i] and a[i+1] (3-way exchange) } } } } ```

Subproblem:

 How can we tell whether the array a is sorted or not ???

 Use the tripwire algorithm

• Detecting a condition

• The tripwire trap is used to detect whether "someone pass a certain area" is true or not

• Set up a tripwire trap:

• If someone kicks/touches the tripwire at least once, the tripwire trap is activated

(And you know someone has passed by the area)

• If the tripwire is intact, then you know no one has pass by the area

(Assuming you are a good trapper and hide the tripwire trap extremely well).

• The tripwire algorithm

 ``` condition = true; // Set the tripwire for ( every case x that needs to be checked ) { if ( x violates the condition ) { condition = false; // Activated the trap ! } } ```

At the end of the loop, you have have:

• condition == true if and only if

 every case has cleared the check

• condition == false if and only if

 some case did not clear the check

• Example: detect if a number n is prime

 ``` isPrime = true; // Set the tripwire /* ==================================== Check every divisor 2, 3, ..., n-1 ==================================== */ for ( i = 2; i < n; i++ ) { if ( n % i == 0 ) // We found a divisor of n ! { isPrime = false; // Activated the trap ! } } ```

At the end of the loop, you have have:

• condition == true if and only if

 n is not divisible by all the numbers 1, 2, ..., n−1

i.e.: n is a prime number

• condition == false if and only if

 n is divisible by some of the numbers 1, 2, ..., n−1

i.e.: n is not a prime number

• Detecting whether an array is sorted

• The tripwire used to detect whether an array is sorted:

• An array is sorted if and only if:

 Every adjacent pair of values are in the correct order

Example:

• The tripwire algorithm in pseudo code:

 ``` done = true; // Set the tripwire (trap) for ( i = 0 ; i < a.length-1 ; i ++ ) { if ( a[i] > a[i+1] ) // Pair out of order { done = false; // Activates the trap } } ```

• The bubble sort algorithm

• The bubble sort algorithm in psuedo code (with the tripwire algorithm:

 ``` public static void sort( double[] a ) { done = false; // Initiaize to start the while loop while ( ! done ) { done = true; // Set the tripwire for ( i = 0 ; i < a.length-1 ; i ++ ) { if ( a[i] > a[i+1] ) // Pair out of order { Swap a[i] and a[i+1] (3-way exchange) done = false; // Array is not completely sorted } } } } ```

• In Java:

 ``` public static void sort(double[] a) { double help; // helper variable for 3-way exchange int i; boolean done; /* --------------------------------------------------- The selection sort algorithm --------------------------------------------------- */ done = false; while ( ! done ) { done = true; // Set tripwire for ( i = 0 ; i < a.length-1 ; i ++ ) { if ( a[i] > a[i+1] ) { /* --------------------------------------------------- Swap a[i] and a[i+1] (3-way exchange) --------------------------------------------------- */ help = a[i]; a[i] = a[i+1]; a[i+1] = help; done = false; // tripwire activated !!! } } } } ```

• A small improvement on the Bubble Sort algorithm

• Fact:

 After 1 iteration, the largest value is in its correct position After 2 iteration, the 2 largest value are in their correct position And so on

• We can shorted the number of items check in each iteration by one

Slightly improved version of the bubble sort:

 ``` public static void sort(double[] a) { double help; // helper variable for 3-way exchange int i, k; // k = last item to be checked boolean done; /* --------------------------------------------------- The selection sort algorithm --------------------------------------------------- */ done = false; k = a.length; // Check all items while ( ! done ) { System.out.print("Step " + (a.length-k) + ": "); System.out.println(Arrays.toString(a) ); done = true; // Set tripwire /* =========================================== Sort the unsort part a[k..n] (n = a.length) =========================================== */ for ( i = 0 ; i < k-1 ; i ++ ) { if ( a[i] > a[i+1] ) { /* --------------------------------------------------- Swap a[i] and a[i+1] (3-way exchange) --------------------------------------------------- */ help = a[i]; a[i] = a[i+1]; a[i+1] = help; done = false; // tripwire activated !!! } } k--; // Shorten the number of pairs checked. } } ```

• Example Program: (Demo above code)

How to run the program:

 Right click on link(s) and save in a scratch directory To compile:   javac testProg1.java To run:          java testProg1

• Bubble Sort using Comparable

• Simply change: doubleComparable and use compareTo()

 ``` public static void sort(Comparable[] a) { Comparable help; // helper variable for 3-way exchange int i, k; boolean done; /* --------------------------------------------------- The selection sort algorithm --------------------------------------------------- */ done = false; k = a.length; while ( ! done ) { System.out.print("Step " + (a.length-k) + ": "); System.out.println(Arrays.toString(a) ); done = true; // Set tripwire /* =========================================== Sort the unsort part a[k..n] (n = a.length) =========================================== */ for ( i = 0 ; i < k-1 ; i ++ ) { if ( a[i].compareTo(a[i+1]) > 0 ) { /* --------------------------------------------------- Swap a[i] and a[i+1] (3-way exchange) --------------------------------------------------- */ help = a[i]; a[i] = a[i+1]; a[i+1] = help; done = false; // tripwire activated !!! } } k--; } } ```

• Example Program: (Demo above code)

How to run the program:

 Right click on link(s) and save in a scratch directory To compile:   javac testProg2.java To run:          java testProg2

• Running time of the Bubble Sort

• Main loop of the Bubble Sort:

 ``` k = a.length; while ( ! done ) { System.out.print("Step " + (a.length-k) + ": "); System.out.println(Arrays.toString(a) ); done = true; // Set tripwire /* =========================================== Sort the unsort part a[k..n] (n = a.length) =========================================== */ for ( i = 0 ; i < k-1 ; i ++ ) { if ( a[i].compareTo(a[i+1]) > 0 ) { /* --------------------------------------------------- Swap a[i] and a[i+1] (3-way exchange) --------------------------------------------------- */ help = a[i]; a[i] = a[i+1]; a[i+1] = help; done = false; // tripwire activated !!! } } k--; } ```

• Best-case running time:

• When Bubble sort receives a sorted array as input, then:

 The while() loop will end after 1 iteration (Because the tripwire will not be activated)

• Therefore:

 Best running time = N statements (Because the for-loop is executed N times)

• Worst-case running time:

• When Bubble sort receives a inversed-sorted array as input, then:

• Each iteration of the while() loop will sort the largest number

The resulting array will also be a inversed-sorted array

Example:

 ``` input: 4 3 2 1 after 1 iter: 3 2 1 4 after 2 iter: 2 1 3 4 ... ```

• Therefore:

• Worst case running time = (N-1) + (N-2) + ... + 2 + 1 statements

(Because the for-loop variable k takes on the values:

 ``` k = N N-1 N-2 .... 2 1 for-loop executed: N-1 N-2 N-3 .... 1 0 times ```

Running time of bubble sort = (N*(N-1))/2