Element | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
Data | 27 | 63 | 1 | 72 | 64 | 58 | 14 | 9 |
1st pass | 1 | 63 | 27 | 72 | 64 | 58 | 14 | 9 |
2nd pass | 1 | 9 | 27 | 72 | 64 | 58 | 14 | 63 |
3rd pass | 1 | 9 | 14 | 72 | 64 | 58 | 27 | 63... |
The selection sort marks the first element (27). It then goes through the remaining data to find the smallest number (1). It swaps this with the first element and the smallest element is now in its correct position. It then marks the second element (63) and looks through the remaining data for the next smallest number (9). These two numbers are then swapped. This process continues until n-1 passes have been made.
Algorithm
for i = 1:n, k = i for j = i+1:n, if a[j] < a[k], k = j → invariant: a[k] smallest of a[i..n] swap a[i,k] → invariant: a[1..i] in final position end
Properties
- Not stable
- O(1) extra space
- Θ(n2) comparisons
- Θ(n) swaps
- Not adaptive
Discussion
From the comparions presented here, one might conclude that selection sort should never be used. It does not adapt to the data in any way (notice that the four animations above run in lock step), so its runtime is always quadratic.
However, selection sort has the property of minimizing the number of swaps. In applications where the cost of swapping items is high, selection sort very well may be the algorithm of choice.
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