SortingSorting

Selection Sort

Repeatedly select the minimum of the unsorted suffix and swap it into place; exactly n−1 swaps.

Learn Selection Sort →
29
0
10
1
14
2
37
3
13
4
5
5
42
6
21
7
1/51Start with 8 elements. Each pass selects the smallest remaining value and places it at the front of the unsorted part.
Current minimumComparingSwappedIn final position
1for i in 0 .. n-2:
2 minIdx = i
3 for j in i+1 .. n-1:
4 if a[j] < a[minIdx]:
5 minIdx = j
6 swap(a[i], a[minIdx])
Complexity
best O(n²)
avg O(n²)
worst O(n²)
space O(1)
Speed