Selection Sort

Find the smallest remaining value and swap it into the next place. One swap per pass.

Python · intermediate · 6 min · 31 steps · free

What you'll learn

selection_sort.py

def selection_sort(items):
    for start in range(len(items) - 1):
        smallest = start
        for i in range(start + 1, len(items)):
            if items[i] < items[smallest]:
                smallest = i
        items[start], items[smallest] = items[smallest], items[start]
    return items

print(selection_sort([29, 10, 14, 37]))

Step by step

  1. Python defines the function selection_sort(). Its body does not run yet: it runs each time the function is called.
  2. Python calls selection_sort(), with items = [29, 10, 14, 37]. It gets its own names.
  3. start is created with the value 0.
  4. smallest starts as the first unsorted index.
  5. i is created with the value 1.
  6. items[i] < items[smallest] is true, so the block under it runs.
  7. 10 < 29: index 1 is the smallest so far.
  8. i changes from 1 to 2.
  9. items[i] < items[smallest] is false, so the block under it is skipped.
  10. i changes from 2 to 3.
  11. items[i] < items[smallest] is false, so the block under it is skipped.
  12. Python moves to the next item of the loop: for i in range(start + 1, len(items)).
  13. The pass is over: swap the smallest (10) into position 0. Position 0 is now final.
  14. start changes from 0 to 1.
  15. Line runs: smallest = start.
  16. i changes from 3 to 2.
  17. items[i] < items[smallest] is true, so the block under it runs.
  18. smallest changes from 1 to 2.
  19. i changes from 2 to 3.
  20. items[i] < items[smallest] is false, so the block under it is skipped.
  21. Python moves to the next item of the loop: for i in range(start + 1, len(items)).
  22. In the list that items points to, index 1 changes from 29 to 14 and index 2 changes from 14 to 29.
  23. start changes from 1 to 2.
  24. Line runs: smallest = start.
  25. Python moves to the next item of the loop: for i in range(start + 1, len(items)).
  26. items[i] < items[smallest] is false, so the block under it is skipped.
  27. Python moves to the next item of the loop: for i in range(start + 1, len(items)).
  28. Line runs: items[start], items[smallest] = items[smallest], items[start].
  29. Python moves to the next item of the loop: for start in range(len(items) - 1).
  30. Sorted: [10, 14, 29, 37].
  31. selection_sort() has finished, so its names are gone. It prints [10, 14, 29, 37].

Common mistakes

Best practices

Key takeaways

Check yourself

Swaps for n items, at most?

Answer: n - 1

Is selection sort faster on sorted input?

Answer: No. It still scans everything.

·

More in Sorting