Insertion Sort

Take the next value and slide it left into its place among the already sorted ones, like sorting cards in your hand.

Python · intermediate · 7 min · 35 steps · free

What you'll learn

insertion_sort.py

def insertion_sort(items):
    for i in range(1, len(items)):
        current = items[i]
        j = i - 1
        while j >= 0 and items[j] > current:
            items[j + 1] = items[j]
            j -= 1
        items[j + 1] = current
    return items

print(insertion_sort([7, 4, 5, 2]))

Step by step

  1. Python defines the function insertion_sort(). Its body does not run yet: it runs each time the function is called.
  2. Python calls insertion_sort(), with items = [7, 4, 5, 2]. It gets its own names.
  3. i is created with the value 1.
  4. current = 4 is the card to insert into the sorted part [7].
  5. j is created with the value 0.
  6. j >= 0 and items[j] > current is true, so the loop body runs.
  7. 7 is bigger than 4, so 7 shifts one place right.
  8. j changes from 0 to -1.
  9. j >= 0 and items[j] > current is false, so the loop ends.
  10. 4 goes into the gap: [4, 7] is sorted.
  11. i changes from 1 to 2.
  12. current changes from 4 to 5.
  13. j changes from -1 to 1.
  14. j >= 0 and items[j] > current is true, so the loop body runs.
  15. In the list that items points to, index 2 changes from 5 to 7.
  16. j changes from 1 to 0.
  17. j >= 0 and items[j] > current is false, so the loop ends.
  18. In the list that items points to, index 1 changes from 7 to 5.
  19. i changes from 2 to 3.
  20. Now 2: smaller than everything sorted so far.
  21. j changes from 0 to 2.
  22. j >= 0 and items[j] > current is true, so the loop body runs.
  23. In the list that items points to, index 3 changes from 2 to 7.
  24. j changes from 2 to 1.
  25. j >= 0 and items[j] > current is true, so the loop body runs.
  26. In the list that items points to, index 2 changes from 7 to 5.
  27. j changes from 1 to 0.
  28. j >= 0 and items[j] > current is true, so the loop body runs.
  29. In the list that items points to, index 1 changes from 5 to 4.
  30. j changes from 0 to -1.
  31. j >= 0 and items[j] > current is false, so the loop ends.
  32. All three shifted; 2 lands at the front.
  33. Python moves to the next item of the loop: for i in range(1, len(items)).
  34. The function returns items.
  35. insertion_sort() has finished, so its names are gone. It prints [2, 4, 5, 7].

Common mistakes

Best practices

Key takeaways

Check yourself

Insertion sort on already sorted data?

Answer: O(n). No shifts needed.

What does the while loop do?

Answer: Shifts bigger values right

·

More in Sorting