Data structures problem 11 of 30

Insertion sort

  • Data structures
  • Easy

Implement insertion_sort(nums), which sorts the list in place and returns it. Do not use sort or sorted.

insertion_sort([5, 2, 4, 6, 1, 3])
# [1, 2, 3, 4, 5, 6]
Show hint

Like sorting a hand of cards: take the next card and slide it left past every larger card.

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

Everything left of i is always sorted. Each new item shifts larger items right until it finds its place. The worst case is O(n2), but on nearly sorted data it is close to O(n), and it is stable. Python's built-in sort (Timsort) uses insertion sort for short runs for exactly that reason.

Want a problem like this every day? See today's problem and keep a streak going.