Learn / How to think

Basic sorts

Five ways to put an array in order, from the simple O(n²) ones to merge sort and quick sort, and how merge sort's merge step can count things while it sorts.

How to recognise it

  • The problem says "sort" or "implement" a named sorting algorithm.
  • The answer would be easy if the array were sorted (finding duplicates, closest pairs, the k-th smallest).
  • You must count pairs (i, j) with i < j that break some order, such as inversions. Merge sort can count them while it merges.
  • You need to sort without extra memory, or need a sort that keeps equal items in their original order.

The idea in one picture

Think of sorting a hand of playing cards. Different people do it differently:

  • Selection: find the smallest card, put it first; find the next smallest, put it second; and so on.
  • Bubble: walk along the hand swapping any neighbouring pair in the wrong order, again and again, until no swaps happen.
  • Insertion: pick up cards one at a time and slide each into its place among the cards already in your hand.
  • Merge: split the deck in half, have two friends sort the halves, then merge the two sorted piles by repeatedly taking the smaller top card.
  • Quick: pick a pivot card, put everything smaller to its left and everything bigger to its right, then sort each side the same way.

How they compare

SortTypical timeAlready sortedExtra memoryEqual items keep their order?
SelectionO(n²)O(n²)O(1)No
Bubble (early exit)O(n²)O(n)O(1)Yes
InsertionO(n²)O(n)O(1)Yes
MergeO(n log n)O(n log n)O(n)Yes
Quick (middle pivot)O(n log n)O(n log n)O(log n) stackNo

A sort that keeps equal items in their original order is called stable. It matters when you sort records by one field after sorting by another.

Divide and conquer

Merge sort and quick sort both split the problem into smaller problems of the same kind, as in the recursion pattern:

function mergeSort(part):
    if part has 0 or 1 elements:
        return                      # already sorted
    sort the left half              # trust the recursion
    sort the right half
    merge the two sorted halves     # the real work: O(length of part)

There are about log₂ n levels of halving, and each level does O(n) merging in total, so merge sort is O(n log n).

Merge sort as a counting tool

While merging two sorted halves, the moment you take an element from the right half, every element still waiting in the left half is bigger than it and comes before it in the original array. That lets you count pairs such as inversions in O(n log n), instead of checking all n² pairs. "Count inversions" and "Reverse pairs" in this pattern use exactly that.

In real code

Every language has a fast built-in sort (Arrays.sort, std::sort, list.sort), and you should use it in practice. The point of writing these sorts yourself is to learn the ideas inside them: the invariant of the simple sorts, the divide and conquer of merge and quick sort, and the merge step, which comes back in many later problems.

Common mistakes

  • Off-by-one loop bounds, such as comparing nums[j] with nums[j + 1] when j already reaches the last index.
  • In merge sort, forgetting to copy the leftovers of one half after the other runs out.
  • In quick sort, always choosing the first or last element as the pivot, which is O(n²) on already-sorted input.
  • Computing the middle as (low + high) / 2 with very large indexes in Java or C++, where the sum can overflow. low + (high - low) / 2 is safe.

Problems

0 of 8 solved

Check yourself

Which sort finishes in about n steps on an array that is already sorted?

Merge sort on 1,000,000 numbers does roughly how many basic steps?

When merging [2, 5, 9] and [1, 6], the right side's 1 is taken first. How many inversions does that reveal?

What is quick sort's worst case, and when does it happen?