all algorithms
algorithm 07
Selection Sort
Scan the unsorted side for the smallest value. Swap it to the front. Repeat with the next position.
07 / Selection Sort
Find the min, swap it forward
- comparisons
- 0
- result
- —
step 0
- 0
def selection_sort(arr): - 1
n = len(arr) - 2
for i in range(n): - 3
min_idx = i - 4
for j in range(i + 1, n): - 5
if arr[j] < arr[min_idx]: - 6
min_idx = j - 7
arr[i], arr[min_idx] = arr[min_idx], arr[i]
Click Sort to run Selection Sort.
What you just watched
Selection sort always does the same number of comparisons — roughly n²/2, no matter what the array looks like. But it only does at most n − 1 swaps. If swapping is expensive (large records being moved around), this can win over bubble or insertion sort in real benchmarks despite the bigger comparison count.
Conceptually: build the sorted half from the front. After pass k, the smallest k values are in their final places. After n−1 passes, you're done.