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
冒泡排序可视化工具
带动画演示的冒泡排序模拟器,提供单步执行、速度调节、自定义输入数据、实时比较/交换计数器以及伪代码同步高亮。完全在浏览器中运行。
打开工具插入排序可视化工具
动画演示插入排序算法,支持单步执行、速度调节、自定义输入数据,并实时显示比较/写入次数与伪代码高亮。完全在浏览器本地运行。
打开工具选择排序可视化工具
以动画方式演示选择排序(Selection Sort),提供逐步执行、速度调节、自定义输入数据、实时的比较/交换计数器以及伪代码展示。完全在浏览器本地运行。
打开工具归并排序可视化工具
带动画演示的归并排序模拟器,支持单步执行、速度调节、自定义输入数据、实时比较/写入计数器以及伪代码高亮显示。完全在浏览器中运行。
打开工具快速排序可视化工具
动态演示快速排序算法,高亮 pivot 与分区过程,支持单步执行、速度调节、自定义输入数据,并实时显示比较/交换次数与伪代码。直接在浏览器中运行。
打开工具堆排序可视化工具
动态演示堆排序算法,支持单步执行、速度调节、自定义输入数据,并实时显示比较/交换计数与伪代码。直接在浏览器中运行。
打开工具Prefer a focused tool?
- Sort Visualizer → Watch sorting algorithms run, step by step
常见问题
什么是堆排序?
堆排序先从数组构建一个最大堆,然后反复将堆顶(最大)元素与末尾元素交换,并执行下沉操作恢复堆的性质,从而从数组右侧逐步扩大已排序区域。
堆排序的时间复杂度是多少?
无论最好、平均还是最坏情况都是 O(n log n)。构建堆需要 O(n) 时间,之后 n 次取出元素的操作每次耗费 O(log n)。
堆排序是稳定排序吗?
不是。堆操作会交换相距较远的元素,这可能改变相等值之间的相对顺序。
堆排序与快速排序相比如何?
堆排序能保证最坏情况下 O(n log n) 的时间复杂度,且只需 O(1) 的额外空间,但由于快速排序具有更好的缓存局部性(cache locality)和更小的常数因子,实际运行中通常更快。