Z

Sorting Algorithms

Bubble, insertion, merge, quick & heap sort — compared and visualized

Sorting is the classic lens for learning algorithm analysis: every method produces the same ordered output, but the cost of getting there ranges from O(n²) to O(n log n). Watching them side by side makes the trade-offs concrete.

The simple O(n²) sorts

Bubble sort repeatedly swaps adjacent out-of-order pairs; selection sort repeatedly picks the smallest remaining element; insertion sort grows a sorted prefix one element at a time. All three are quadratic in the worst case, but insertion sort shines on small or nearly-sorted inputs, where it approaches O(n).

The divide-and-conquer sorts

Merge sort splits the array in half, sorts each half and merges them, guaranteeing O(n log n) at the cost of extra memory. Quicksort partitions around a pivot and recurses; it is usually the fastest in practice thanks to cache locality, but a poor pivot can degrade it to O(n²). Heap sort builds a binary heap and repeatedly extracts the max, sorting in place in O(n log n) with no extra memory.

Stability & in-place

Two properties decide which sort fits a job: stability (equal keys keep their original order — merge and insertion sort are stable; quick and heap sort are not) and whether the sort works in place (no significant extra memory — quick and heap sort do; merge sort does not). Step through each below to feel the difference.

Try it interactively

Prefer a focused tool?

Frequently asked questions

Which sorting algorithm is fastest?

For general data, the O(n log n) sorts — merge, quick and heap — beat the O(n²) sorts at scale. Quicksort is usually fastest in practice due to cache friendliness, merge sort guarantees O(n log n) worst case, and heap sort sorts in place with no extra memory.

When is a simple O(n²) sort actually a good choice?

Insertion sort is excellent for small arrays (a few dozen elements) and for data that is already nearly sorted, where it approaches O(n). Many production sorts switch to insertion sort for small sub-arrays.

What is a stable sort?

A stable sort preserves the relative order of records with equal keys. Merge sort and insertion sort are stable; quicksort and heap sort are not. Stability matters when you sort by one key after already sorting by another.