Element | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
Data | 27 | 63 | 1 | 72 | 64 | 58 | 14 | 9 |
1st pass | 27 | 1 | 63 | 64 | 58 | 14 | 9 | 72 |
2nd pass | 1 | 27 | 63 | 58 | 14 | 9 | 64 | 72 |
3rd pass | 1 | 27 | 58 | 14 | 9 | 63 | 64 | 72... |
Algorithm
for i = 1:n, swapped = false for j = n:i+1, if a[j] < a[j-1], swap a[j,j-1] swapped = true → invariant: a[1..i] in final position break if not swapped end
Properties
- Stable
- O(1) extra space
- O(n2) comparisons and swaps
- Adaptive: O(n) when nearly sorted
References
Algorithms in Java, Parts 1-4, 3rd edition by Robert Sedgewick. Addison Wesley, 2003.
Programming Pearls by Jon Bentley. Addison Wesley, 1986.
Quicksort is Optimal by Robert Sedgewick and Jon Bentley, Knuthfest, Stanford University, January, 2002.
Bubble-sort with Hungarian ("Csángó") folk dance YouTube video, created at Sapientia University, Tirgu Mures (Marosvásárhely), Romania.
Select-sort with Gypsy folk dance YouTube video, created at Sapientia University, Tirgu Mures (Marosvásárhely), Romania.
The Beauty of Sorting YouTube video, Dynamic Graphics Project, Computer Systems Research Group, University of Toronto.
No comments:
Post a Comment