Merge Sort

Split the array in half, sort each half, merge the two sorted halves. Always O(n log n), stable, and the merge step can count cross pairs, sort a linked list, or sort data that does not fit in memory.

Overview

The idea

Merge sort splits the array in half, sorts each half by the same method, and merges the two sorted halves into one. A single value is already sorted, which is the base case. John von Neumann described the method in 1945.

Four properties follow from that simple plan. It takes O(n log n) time in the best, average and worst case, because every level of merging does n work and there are log2 n levels. It needs O(n) extra space for arrays, because the merge writes into a buffer, but only O(1) beyond the stack for linked lists, because there the merge relinks nodes. It is stable when a tie takes from the left half, so equal values keep their input order. And its access pattern is sequential: it never jumps around, so it suits lists, disks and tapes.

Quicksort is usually faster on arrays in memory, but it has an O(n²) worst case and is not stable. Merge sort is the answer when you need a guaranteed bound, stability, a linked list, or data larger than memory. Every one of those strengths comes from the merge, so that is where we start.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio