Editor

Selection sort in Python

Selection sort finds the smallest value in the unsorted part of the list and swaps it to the front, so the sorted part grows by one value on every pass.

The arrow keys step through it. Edit the code to try your own input.

How it works

  1. Everything left of i is already sorted. Everything from i on is still to do.
  2. Start by guessing that the smallest remaining value is at i, so min_index = i.
  3. Let j scan the rest of the list and move min_index whenever nums[j] is smaller.
  4. Swap the smallest value into position i, then move i one step right.

What to watch

  • Watch min_index jump each time j finds a smaller bar.
  • Watch for exactly one swap per pass: the smallest remaining bar lands at i.
  • Watch j make its full sweep on every pass, even when nothing changes. That is why even a sorted list takes O(n²).

The code

def selection_sort(nums):
    n = len(nums)
    for i in range(n - 1):
        min_index = i              # guess: the smallest is at i
        for j in range(i + 1, n):
            if nums[j] < nums[min_index]:
                min_index = j      # found a smaller one
        nums[i], nums[min_index] = nums[min_index], nums[i]
    return nums

data = [7, 3, 9, 1, 5, 2]
print(selection_sort(data))
Output
[1, 2, 3, 5, 7, 9]

Open it in the editor · Python Program for Selection Sort, explained