Selection Sort
Repeatedly pick the smallest remaining value and swap it to the front. Always n(n − 1)/2 comparisons, but at most n − 1 swaps.
SolvesSorting
- best
- O(n^2)
- average
- O(n^2)
- worst
- O(n^2)
- space
- O(1)
Selection sort builds the result from the front. Each round it looks at everything that is still unsorted, finds the smallest value and puts it next in line.
Already sorted: every pass finds its minimum in place, so no value moves. It still makes n(n − 1)/2 comparisons: Θ(n²).
1def selection_sort(a):2 n = len(a)3 for i in range(n - 1):4 smallest = i5 # find the smallest value in a[i..n)6 for j in range(i + 1, n):7 if a[j] < a[smallest]:8 smallest = j9 a[i], a[smallest] = a[smallest], a[i]10 return aa[0..-1] holds the 0 smallest values. Find the next one.
- comparisons
- 0
- swaps
- 0
How it works
The array is split into a sorted prefix a[0..i) and the unsorted rest. The prefix holds the
i smallest values in their final places [1].
- Assume
a[i]is the smallest value of the rest. - Scan
a[i+1..n). Whenever a value is smaller, remember its index. - Swap the smallest value with
a[i]. The prefix is now one value longer.
After rounds the last value is also in place.
Complexity
| Case | Input | Comparisons | Swaps | Time |
|---|---|---|---|---|
| Best | sorted | |||
| Average | random | |||
| Worst | small value at the end |
The scan never stops early, so the comparisons do not depend on the input. Round compares pairs. The swaps are always , but on sorted input each one swaps a value with itself.
Implementations
- Standard: one scan per round, one swap per round.
Pitfalls
- The sort is not stable. Swapping
a[i]with a far-away minimum can jump over an equal value. Sorting[2a, 2b, 1]gives[1, 2b, 2a]. - Sorted input is not faster. Selection sort cannot see that the rest is already in order.
Related
References
- T. H. Cormen et al., Introduction to Algorithms, 3rd ed., MIT Press, 2009.
Further reading
- D. E. Knuth, The Art of Computer Programming, Volume 3: Sorting and Searching, 2nd ed., Addison-Wesley, 1998.
- K. Mehlhorn and P. Sanders, Algorithms and Data Structures: The Basic Toolbox, Springer, 2008.