1. Selection sort
In pass (starting at 0), selection sort finds the minimum of a[i..n-1] and swaps it into position i. After pass the first items are the smallest ones, in final order.
def selection_sort(a):
n = len(a)
for i in range(n - 1):
m = i
for j in range(i + 1, n):
if a[j] < a[m]:
m = j
a[i], a[m] = a[m], a[i]
- Comparisons: always , whatever the input. So best, average and worst case are all .
- Swaps: at most , one per pass. This is the fewest swaps of the three algorithms, which matters when writes are costly.
- In-place: extra space.
- Not stable: the long-distance swap can jump an item over an equal one. For
[2a, 2b, 1]the first pass swaps2aand1, giving[1, 2b, 2a]. - Not adaptive: a sorted input still costs comparisons.
Selection sort can also be written to select the maximum and place it at the end; check which version the question uses.