2016-12-15

posted Dec 15, 2016, 7:04 AM by Samuel Konstantinovich   [ updated Dec 15, 2016, 6:25 PM ]
Goal: Bubble Sort

Time testing your sorts!

The next O(n2) sort we will learn is the bubble sort.

Similar to the other O(n2) sorts we learned, this runs through each element, and does a linear pass on each. The bubble sort starts at the 1st element, and compares adjacent elements of the array up until the end. If an adjacent pair is out of order it swaps them. Ultimately this places the largest element into the last position.

The next pass, the algorithm starts at the 1st element again, except it will stop 1 element early, because the largest elment has been moved to the correct index after the first pass.

Repeat this N times, but if no swaps have been made, stop the sort.



First Pass

5 1 4 2 8 ) {\displaystyle \to }\to  ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) {\displaystyle \to }\to  ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) {\displaystyle \to }\to  ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) {\displaystyle \to }\to  ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

Second Pass

1 4 2 5 8 ) {\displaystyle \to }\to  ( 1 4 2 5 8 )
( 1 4 2 5 8 ) {\displaystyle \to }\to  ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) {\displaystyle \to }\to  ( 1 2 4 5 8 )
( 1 2 4 5 8 ) {\displaystyle \to }\to  ( 1 2 4 5 8 ) //This is not a required check since you know 8 is in place.

Now, the array is already sorted, but the algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.

Third Pass

1 2 4 5 8 ) {\displaystyle \to }\to  ( 1 2 4 5 8 )
( 1 2 4 5 8 ) {\displaystyle \to }\to  ( 1 2 4 5 8 )
( 1 2 4 5 8 ) {\displaystyle \to }\to  ( 1 2 4 5 8 ) //This is not a required check since you know 5 is in place.
( 1 2 4 5 8 ) {\displaystyle \to }\to  ( 1 2 4 5 8 ) //This is not a required check since you know 8 is in place.

Comments