Skip to content
SimpleScope

Sorting

Quick sort vs Heap sort

Quick sort and Heap sort both put an array in order, in different ways. Quick sort: divide and conquer: partition around a pivot. Heap sort: build a max-heap in the array, then repeatedly move the largest value to the end. In the worst case heap sort takes O(n log n) while quick sort takes O(n²), so heap sort scales better on large inputs.

At a glance

PropertyQuick sortHeap sort
TechniqueDivide and conquer: partition around a pivotBuild 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²)O(n log n)
Extra spaceO(log n)O(1)
Stable (equal values keep their order)NoNo
In place (no extra array)YesYes
Needs sorted inputNoNo

When to choose each

Choose quick sort when

you want a fast in-place sort on typical data.

Avoid it when

you need a worst-case guarantee or a stable sort.

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).

InputQuick sortHeap sort
Mixed3143
Already sorted7553
Reversed5140
Nearly sorted6550
Duplicates2936

See them run

More comparisons