Bubble Sort
Bubble Sort: Algorithm Assume that we use an array of integers A with N elements. for (p = 0; p < N; p++) // pass p for (e = 1; e < N - p; e++) // sort sub-array A[0...(N-p)] if (A[e-1] > A[e]) // sort in non-decreasing order Swap(A[e-1], A[e]);
Bubble-Sort on a Sequence Original data sequence: 5 7 2 6 9 3 ================= 5 2 7 6 9 3 5 2 6 7 9 3 5 2 6 7 3 9 ==End of Pass 1==== 2 5 6 7 3 | 9 2 5 6 3 7 | 9 ==End of Pass 2==== 2 5 3 6 | 7 9 ==End of Pass 3==== 2 3 5 | 6 7 9 ==End of Pass 4====
Analysis: Best Case and Worst Case If the given list is ordered in reverse order, we do: N(N-1) comparisons (if statement) N(N-1) swaps (function Swap()) If the given list is ordered in “random” order, we do: N(N-1) comparisons less than N(N-1) swaps If the given list is already sorted, we do: no swaps In all 3 cases, the running time is O(N2) due to N(N-1) comparisons.
Optimizing the Bubble Sort The previous algorithm can be optimized, if the program stops as soon as it is detected that no swap has been made during a pass. In this case, a Boolean variable swapped can be used, that is set to FALSE at the beginning of every pass. swapped will then be set to TRUE whenever a swap is made. At the end of a pass, if swapped still keeps the value FALSE, the program stops.
Optimizing the Bubble Sort swapped = TRUE; for (p = 0; p < N && swapped; p++) // pass p { swapped = FALSE; for (e = 1; e < N - p; e++) // sort sub-array A[0...(N-p)] if (A[e-1] > A[e]) swap(A[e-1], A[e]); } If the given list is already sorted, only (N-1) comparisons need to be done before the program stops. So the best-case running time of the optimized Bubble Sort is W(N).