AP® Computer Science A · Unit 4 · Topic 4.17

Merge Sort: Split, Sort, Merge

Merge sort splits an array in half again and again until each piece has one element, then merges those pieces back together in sorted order using two pointers at a time.

Merging two already-sorted lists is easy: look at the front of each list, take the smaller front element, move it to the result, and repeat. Since both lists are sorted, the smallest remaining element is always sitting at one of the two fronts, so you never have to search. Merge sort builds on this by recursion. It splits the array in half, sorts each half by calling itself, then merges the two sorted halves using that simple two-pointer walk. A single element counts as already sorted, so the splitting stops there and the merging begins.

Each split cuts the problem size roughly in half, so an array of n elements needs about log2(n) levels of splitting before every piece is down to one element. At that bottom level there is nothing to do but merge pairs back up, level by level, until the whole array is one sorted list again. At each level, merging all the pieces together touches every element once, so the total work is proportional to n per level, times log2(n) levels, giving n log n overall.

That n log n growth is why merge sort pulls ahead of insertion sort on large arrays. Insertion sort shifts elements in place and avoids extra memory, but its worst-case work grows as n squared, since each new element can require sliding past many already-placed ones. Merge sort copies elements into new arrays at every merge step, which costs extra memory and overhead, but n log n grows so much slower than n squared that on large inputs the copying cost is outweighed many times over.

Key terms

Merge
Combining two sorted lists into one sorted list by repeatedly taking the smaller of the two front elements.
Recursion
A method solving a problem by calling itself on smaller pieces until it reaches a piece simple enough to solve directly.
Two-pointer walk
Tracking a position in each of two sorted lists and advancing whichever pointer's element was just used.
n log n
A growth rate describing total work that comes from doing n units of work at each of about log2(n) levels of splitting.

Watch it explained

  1. How it worksHow does merge sort keep splitting until every piece holds a single element?
  2. Worked exampleTrace merge sort on {8, 3, 5, 1, 9, 2} through every split and every merge.
  3. How it worksHow does the merge step walk two sorted lists with two pointers moving at once?
  4. Worked exampleFind how many levels of splitting merge sort needs for an array of 16 elements.
  5. Ties togetherHow does merge sort beat insertion sort on big arrays despite copying so much more?

Check yourself

Your turn1 of 2
Merge sort keeps splitting an array of 28 elements in half until every piece holds a single element. How many levels of splitting does this take?

End of topic.