跳到主要内容
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?

常见问题

什么是堆排序?

堆排序先从数组构建一个最大堆,然后反复将堆顶(最大)元素与末尾元素交换,并执行下沉操作恢复堆的性质,从而从数组右侧逐步扩大已排序区域。

堆排序的时间复杂度是多少?

无论最好、平均还是最坏情况都是 O(n log n)。构建堆需要 O(n) 时间,之后 n 次取出元素的操作每次耗费 O(log n)。

堆排序是稳定排序吗?

不是。堆操作会交换相距较远的元素,这可能改变相等值之间的相对顺序。

堆排序与快速排序相比如何?

堆排序能保证最坏情况下 O(n log n) 的时间复杂度,且只需 O(1) 的额外空间,但由于快速排序具有更好的缓存局部性(cache locality)和更小的常数因子,实际运行中通常更快。