Merge Sort

Split the list in half until each piece has one item, then merge the sorted pieces back together. Divide and conquer.

Python · intermediate · 10 min · 74 steps · free

What you'll learn

merge_sort.py

def merge(left, right):
    result = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    result.extend(left[i:])
    result.extend(right[j:])
    return result

def merge_sort(items):
    if len(items) <= 1:
        return items
    mid = len(items) // 2
    left = merge_sort(items[:mid])
    right = merge_sort(items[mid:])
    return merge(left, right)

print(merge_sort([5, 2, 4, 1]))

Step by step

  1. Python defines the function merge(). Its body does not run yet: it runs each time the function is called.
  2. Python defines the function merge_sort(). Its body does not run yet: it runs each time the function is called.
  3. Python calls merge_sort(), with items = [5, 2, 4, 1]. It gets its own names.
  4. len(items) <= 1 is false, so the block under it is skipped.
  5. mid is created with the value 2.
  6. merge_sort splits [5, 2, 4, 1] and calls itself on the left half [5, 2].
  7. len(items) <= 1 is false, so the block under it is skipped.
  8. mid is created with the value 1.
  9. Python calls merge_sort() #3, with items = [5]. It gets its own names.
  10. One item: already sorted. This is the base case.
  11. The function returns items.
  12. merge_sort() #3 has finished, so its names are gone. The value it returned, [5], is stored in left.
  13. Python calls merge_sort() #3, with items = [2]. It gets its own names.
  14. len(items) <= 1 is true, so the block under it runs.
  15. The function returns items.
  16. merge_sort() #3 has finished, so its names are gone. The value it returned, [2], is stored in right.
  17. Both halves are sorted ([5] and [2]): merge them.
  18. result is created and points to a new list: [].
  19. i is created with the value 0. j is created with the value 0.
  20. i < len(left) and j < len(right) is true, so the loop body runs.
  21. merge takes the smaller front item each time: 2 before 5.
  22. 2 is added to the end of the list that result points to.
  23. j changes from 0 to 1.
  24. i < len(left) and j < len(right) is false, so the loop ends.
  25. 5 is added to the end of the list that result points to.
  26. Line runs: result.extend(right[j:]).
  27. The function returns result.
  28. merge() has finished, so its names are gone.
  29. [5, 2] became [2, 5].
  30. Python calls merge_sort() #2, with items = [4, 1]. It gets its own names.
  31. len(items) <= 1 is false, so the block under it is skipped.
  32. mid is created with the value 1.
  33. Python calls merge_sort() #3, with items = [4]. It gets its own names.
  34. len(items) <= 1 is true, so the block under it runs.
  35. The function returns items.
  36. merge_sort() #3 has finished, so its names are gone. The value it returned, [4], is stored in left.
  37. Python calls merge_sort() #3, with items = [1]. It gets its own names.
  38. len(items) <= 1 is true, so the block under it runs.
  39. The function returns items.
  40. merge_sort() #3 has finished, so its names are gone. The value it returned, [1], is stored in right.
  41. Python calls merge(), with left = [4] and right = [1]. It gets its own names.
  42. result is created and points to a new list: [].
  43. i is created with the value 0. j is created with the value 0.
  44. i < len(left) and j < len(right) is true, so the loop body runs.
  45. left[i] <= right[j] is false, so the block under it is skipped.
  46. 1 is added to the end of the list that result points to.
  47. j changes from 0 to 1.
  48. i < len(left) and j < len(right) is false, so the loop ends.
  49. 4 is added to the end of the list that result points to.
  50. Line runs: result.extend(right[j:]).
  51. The function returns result.
  52. merge() has finished, so its names are gone.
  53. merge_sort() #2 has finished, so its names are gone. The value it returned, [1, 4], is stored in right.
  54. The last merge: [2, 5] and [1, 4].
  55. result is created and points to a new list: [].
  56. i is created with the value 0. j is created with the value 0.
  57. i < len(left) and j < len(right) is true, so the loop body runs.
  58. left[i] <= right[j] is false, so the block under it is skipped.
  59. 1 is added to the end of the list that result points to.
  60. j changes from 0 to 1.
  61. i < len(left) and j < len(right) is true, so the loop body runs.
  62. left[i] <= right[j] is true, so the block under it runs.
  63. 2 is added to the end of the list that result points to.
  64. i changes from 0 to 1.
  65. i < len(left) and j < len(right) is true, so the loop body runs.
  66. left[i] <= right[j] is false, so the block under it is skipped.
  67. 4 is added to the end of the list that result points to.
  68. j changes from 1 to 2.
  69. i < len(left) and j < len(right) is false, so the loop ends.
  70. One side ran out; the rest of the other side is added as it is.
  71. Line runs: result.extend(right[j:]).
  72. The function returns result.
  73. merge() has finished, so its names are gone.
  74. merge_sort() has finished, so its names are gone. It prints [1, 2, 4, 5].

Common mistakes

Best practices

Key takeaways

Check yourself

How many levels of splitting for 8 items?

Answer: 3. 8 → 4 → 2 → 1.

Merging two sorted lists of total size n costs?

Answer: O(n)

·

More in Sorting