Selection sort
Simple sorts · Article 2 of 8 · 3 min read
The easiest sort to explain: find the smallest item, put it first, repeat.
The short version
Selection sort scans the unsorted part for the smallest item and swaps it to the front. Then it repeats on what is left.
Details
It always does about n squared comparisons, even on a list that is already sorted. It makes few swaps, which matters only when writing is expensive.
Try it yourself
def selection_sort(items):
for i in range(len(items)):
smallest = i
for j in range(i + 1, len(items)):
if items[j] < items[smallest]:
smallest = j
items[i], items[smallest] = items[smallest], items[i]
data = [5, 2, 9, 1]
selection_sort(data)
print(data)
You should see [1, 2, 5, 9].
Explain it to the duck
Why does selection sort take the same time on a sorted list as on a shuffled one?
Tested with: Python 3.13.