Download presentation
Presentation is loading. Please wait.
1
Bubble Sort
2
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]);
3
Bubble-Sort on a Sequence
Original data sequence: ================= ==End of Pass 1==== | 9 | 9 ==End of Pass 2==== | 7 9 ==End of Pass 3==== 2 3 5 | 6 7 9 ==End of Pass 4====
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.
5
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.
6
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).
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.