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
- Everything left of
iis already sorted. Everything fromion is still to do. - Start by guessing that the smallest remaining value is at
i, somin_index = i. - Let
jscan the rest of the list and movemin_indexwhenevernums[j]is smaller. - Swap the smallest value into position
i, then moveione step right.
What to watch
- Watch
min_indexjump each timejfinds a smaller bar. - Watch for exactly one swap per pass: the smallest remaining bar lands at
i. - Watch
jmake 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