Skip to content
SimpleScope

Sorting

Merge sort vs Heap sort

Merge sort and Heap sort both put an array in order, in different ways. Merge sort: divide and conquer: split, sort each half, merge. Heap sort: build a max-heap in the array, then repeatedly move the largest value to the end. In the worst case both take O(n log n), so the choice comes down to the other differences below.

At a glance

PropertyMerge sortHeap sort
TechniqueDivide and conquer: split, sort each half, mergeBuild a max-heap in the array, then repeatedly move the largest value to the end
Best case timeO(n log n)O(n log n)
Average case timeO(n log n)O(n log n)
Worst case timeO(n log n)O(n log n)
Extra spaceO(n)O(1)
Stable (equal values keep their order)YesNo
In place (no extra array)NoYes
Needs sorted inputNoNo

When to choose each

Choose merge sort when

you need a guaranteed O(n log n) time or a stable sort.

Avoid it when

memory is tight.

Choose heap sort when

you need a guaranteed O(n log n) time and almost no extra memory.

Avoid it when

you need a stable sort, or the fastest sort on typical data.

The same inputs, counted

These numbers come from running both real implementations: operations (comparisons plus writes, a swap counting as two writes).

InputMerge sortHeap sort
Mixed3443
Already sorted3153
Reversed2940
Nearly sorted3150
Duplicates3236

See them run

More comparisons