Skip to content
SimpleScope

Sorting

Bubble sort vs Heap sort

Bubble sort and Heap sort both put an array in order, in different ways. Bubble sort: swap neighbors that are out of order. 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 bubble sort takes O(n²), so heap sort scales better on large inputs.

At a glance

PropertyBubble sortHeap sort
TechniqueSwap neighbors that are out of orderBuild a max-heap in the array, then repeatedly move the largest value to the end
Best case timeO(n)O(n log n)
Average case timeO(n²)O(n log n)
Worst case timeO(n²)O(n log n)
Extra spaceO(1)O(1)
Stable (equal values keep their order)YesNo
In place (no extra array)YesYes
Needs sorted inputNoNo

When to choose each

Choose bubble sort when

you want the simplest sort to explain, on tiny or almost sorted data.

Avoid it when

the data is large.

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

InputBubble sortHeap sort
Mixed4043
Already sorted653
Reversed6340
Nearly sorted1350
Duplicates4736

See them run

More comparisons