Data Structures · Sorting

Merge sort

Merge sort splits the array in half, sorts each half, and merges the two sorted halves back together. Because each level of splitting halves the problem, it sorts n values in O(n log n) time, every time, which is far faster than selection or insertion sort on large arrays.

Divide, conquer, combine

Merge sort is a divide and conquer algorithm. To sort arr[left..right]:

  1. Divide: find the middle, mid = left + (right - left) / 2, splitting the range into a left half and a right half.
  2. Conquer: sort each half by calling merge sort on it, recursively.
  3. Combine: merge the two sorted halves into one sorted range.

The recursion stops at the base case: a range with one element (or none) is already sorted, so there is nothing to do. All the real work happens in the merge step.

Merging two sorted lists is easy because their smallest values are at the front. Compare the two front values, copy the smaller one out, and move past it. Repeat until one list is used up, then copy the rest of the other. Each comparison places one value, so merging k values takes at most k − 1 comparisons.

A worked example

Sorting {38, 27, 43, 3, 9, 82, 10}. Going down, each range is split in half until only single values are left. Going up, neighboring pieces are merged into sorted runs.

Try it

The array

The range being sorted Outside this call's range Position k being filled Filled by this merge

Call stack

    Variables

    What is happening

    main.cpp

      The array in main() changes to match what you sort.

      Why it is O(n log n)

      The number of levels. Each split halves the range, so after about log₂ n levels every piece has one element. Seven values need 3 levels; a million values need only 20.

      The work per level. On any one level, the merges together handle every value once, so each level costs about n steps.

      Multiply the two: about n values × log₂ n levels. As a recurrence, the time to sort n values is

      T(n) = 2 T(n/2) + n  ⇒  T(n) = O(n log n)

      Merge sort always splits in the middle and always merges, whatever the data, so this holds in the best, average and worst case.

      Memory. The merge step copies each half into temporary vectors, so merge sort needs O(n) extra space. It is not in place, unlike selection and insertion sort.

      Stability. When the two front values are equal, the merge takes the one from the left half first (L[i] <= R[j]). Equal values therefore keep their original order: merge sort is stable. Try the Equal values preset.

      Comparisons, counted

      Merge sort is run on random arrays of each size and its comparisons are counted. Selection sort always makes n(n − 1)/2.

      Strengths and weaknesses

      Strengths
      • O(n log n) in every case: no bad inputs.
      • Stable: equal values keep their order.
      • Works well on linked lists and on data too big for memory, because it reads its input in order.
      Weaknesses
      • Needs O(n) extra memory for the temporary halves.
      • On very small arrays, the recursion and copying cost more than a simple sort. Practical versions switch to insertion sort for small pieces.
      • Not adaptive: an already sorted array still takes n log n work.

      Think first

      What is the base case, and why is it already sorted?

      A range with left >= right has at most one element. A single value is in order by itself, so mergeSort returns without doing anything.

      Merging {3, 27, 38, 43} with {9, 10, 82}: how many comparisons?

      Six. 3 vs 9, 27 vs 9, 27 vs 10, 27 vs 82, 38 vs 82, 43 vs 82. Then the left half is used up and 82 is copied without a comparison. Merging k values takes at most k − 1 comparisons.

      Why compute mid as left + (right − left) / 2 instead of (left + right) / 2?

      They give the same answer, but left + right can overflow an int for very large arrays. right - left never does.

      What would happen to stability if the merge used < instead of <=?

      With L[i] < R[j], a tie would take the value from the right half first, so equal values could swap order. The sort would still be correct, but no longer stable.