Skip to main content
CodeFlow
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

42017188273355431596624761889
comparisons
0
result
step 0
  1. 0def selection_sort(arr):
  2. 1 n = len(arr)
  3. 2 for i in range(n):
  4. 3 min_idx = i
  5. 4 for j in range(i + 1, n):
  6. 5 if arr[j] < arr[min_idx]:
  7. 6 min_idx = j
  8. 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.