Algorithms Made Simple

Merge Sort vs Quicksort: Trading Memory, Speed and Stability

Why n log n beats n squared, and what each fast sorting method gives up to get there.

Algorithms Made Simple · 5 min read

Simple sorting methods slow down sharply as lists grow. Merge sort and quicksort avoid that by dividing the work, and each pays for it differently.

The slow baseline

Elementary methods such as selection sort or insertion sort compare items in nested loops, so the work grows with n squared. For a million items that is on the order of a trillion steps. Fast sorting methods grow like n log n, which is about 20 million steps for the same list.

Merge sort

Split the list in half, sort each half the same way, then merge the two sorted halves by repeatedly taking the smaller front item. It always takes n log n time and it is stable, meaning equal items keep their original order. The cost is extra memory for merging.

Quicksort

Pick a pivot, move smaller items to one side and larger to the other, then sort each side. It works in place and is very fast in practice. But with consistently bad pivots, for example always taking the first item of an already-sorted list, it degrades to n squared. Choosing pivots at random or by median-of-three makes that unlikely.

In real libraries

Many standard libraries use hybrids. Python’s built-in sort, for example, combines merge-style merging with insertion sort on small runs, and it is stable. You rarely need to write your own sort, but knowing the trade-offs helps you choose when stability or memory matters.

More guides from this book