交互实验室在浏览器中运行

二叉堆与堆排序

最大堆/最小堆双视图联动演示,支持上浮、下沉与堆排序全流程。

速度:
以数组存储的大顶堆:下标 i 的子节点位于 2i+1 和 2i+2。
907580456055702035
同一个堆的数组形式
90
[0]
75
[1]
80
[2]
45
[3]
60
[4]
55
[5]
70
[6]
20
[7]
35
[8]

关于本工具

二叉堆是一棵用普通数组存储的完全二叉树:下标 i 的孩子在 2i+1 和 2i+2,父节点在 ⌊(i−1)/2⌋。大顶堆中每个父节点都不小于孩子(小顶堆相反),所以堆顶永远是最大(或最小)值。它是实现优先队列的标准方式。

本实验室把树和数组并排绘制,动画演示插入时的上浮、取出堆顶时的下沉、O(n) 的自底向上建堆以及堆排序。切换大顶堆与小顶堆,可以看到顺序相反的同一套操作。

使用方法 二叉堆与堆排序

  1. 选择大顶堆或小顶堆。切换时会把当前数据重建为新类型的合法堆。
  2. 插入一个值:它先放到数组末尾,只要比父节点“更优”就向上交换。
  3. 取出堆顶:最后一个元素移到根,再与较大(或较小)的孩子交换,逐层下沉。
  4. 运行“建堆”或“堆排序”,逐步观察完整算法,数组下标会同步高亮。

示例

向大顶堆插入

输入
[50, 30, 40, 10, 20] 插入 45
结果
45 追加到下标 5,与父节点 40 交换 → [50, 30, 45, 10, 20, 40]

取出最大值

输入
[50, 30, 45, 10, 20, 40]
结果
返回 50;40 移到根并下沉 → [45, 30, 40, 10, 20]

堆排序

输入
[4, 10, 3, 5, 1]
结果
[1, 3, 4, 5, 10]——先建大顶堆,再反复把堆顶换到末尾

五种语言的代码实现

同一算法的 Python、JavaScript、Java、Go 和 C++ 实现。每段程序都完整可运行,注释中标出了它的输出结果。

class MinHeap:
    def __init__(self):
        self.a = []

    def push(self, x):
        a = self.a
        a.append(x)
        i = len(a) - 1
        while i > 0:                      # sift up
            parent = (i - 1) // 2
            if a[parent] <= a[i]:
                break
            a[parent], a[i] = a[i], a[parent]
            i = parent

    def pop(self):
        a = self.a
        top = a[0]
        last = a.pop()
        if a:
            a[0] = last
            i, n = 0, len(a)
            while True:                   # sift down
                left, right, smallest = 2 * i + 1, 2 * i + 2, i
                if left < n and a[left] < a[smallest]:
                    smallest = left
                if right < n and a[right] < a[smallest]:
                    smallest = right
                if smallest == i:
                    break
                a[i], a[smallest] = a[smallest], a[i]
                i = smallest
        return top

    def __len__(self):
        return len(self.a)


h = MinHeap()
for x in [5, 3, 8, 1, 9, 2]:
    h.push(x)
print(h.a)                                    # [1, 3, 2, 5, 9, 8]
print([h.pop() for _ in range(len(h))])       # [1, 2, 3, 5, 8, 9]
class MinHeap {
  constructor() {
    this.a = [];
  }

  get size() {
    return this.a.length;
  }

  push(x) {
    const a = this.a;
    a.push(x);
    let i = a.length - 1;
    while (i > 0) { // sift up
      const parent = (i - 1) >> 1;
      if (a[parent] <= a[i]) break;
      [a[parent], a[i]] = [a[i], a[parent]];
      i = parent;
    }
  }

  pop() {
    const a = this.a;
    const top = a[0];
    const last = a.pop();
    if (a.length > 0) {
      a[0] = last;
      let i = 0;
      const n = a.length;
      for (;;) { // sift down
        const left = 2 * i + 1, right = 2 * i + 2;
        let smallest = i;
        if (left < n && a[left] < a[smallest]) smallest = left;
        if (right < n && a[right] < a[smallest]) smallest = right;
        if (smallest === i) break;
        [a[i], a[smallest]] = [a[smallest], a[i]];
        i = smallest;
      }
    }
    return top;
  }
}

const h = new MinHeap();
for (const x of [5, 3, 8, 1, 9, 2]) h.push(x);
console.log(h.a.join(', ')); // 1, 3, 2, 5, 9, 8
const sorted = [];
while (h.size > 0) sorted.push(h.pop());
console.log(sorted.join(', ')); // 1, 2, 3, 5, 8, 9
import java.util.ArrayList;
import java.util.List;

public class Main {
    static class MinHeap {
        final List<Integer> a = new ArrayList<>();

        int size() { return a.size(); }

        void push(int x) {
            a.add(x);
            int i = a.size() - 1;
            while (i > 0) {                       // sift up
                int parent = (i - 1) / 2;
                if (a.get(parent) <= a.get(i)) break;
                swap(parent, i);
                i = parent;
            }
        }

        int pop() {
            int top = a.get(0);
            int last = a.remove(a.size() - 1);
            if (!a.isEmpty()) {
                a.set(0, last);
                int i = 0, n = a.size();
                while (true) {                    // sift down
                    int left = 2 * i + 1, right = 2 * i + 2, smallest = i;
                    if (left < n && a.get(left) < a.get(smallest)) smallest = left;
                    if (right < n && a.get(right) < a.get(smallest)) smallest = right;
                    if (smallest == i) break;
                    swap(i, smallest);
                    i = smallest;
                }
            }
            return top;
        }

        private void swap(int i, int j) {
            int t = a.get(i);
            a.set(i, a.get(j));
            a.set(j, t);
        }
    }

    public static void main(String[] args) {
        MinHeap h = new MinHeap();
        for (int x : new int[] {5, 3, 8, 1, 9, 2}) h.push(x);
        System.out.println(h.a);          // [1, 3, 2, 5, 9, 8]
        List<Integer> sorted = new ArrayList<>();
        while (h.size() > 0) sorted.add(h.pop());
        System.out.println(sorted);       // [1, 2, 3, 5, 8, 9]
    }
}
package main

import "fmt"

type MinHeap struct{ a []int }

func (h *MinHeap) Len() int { return len(h.a) }

func (h *MinHeap) Push(x int) {
	h.a = append(h.a, x)
	i := len(h.a) - 1
	for i > 0 { // sift up
		parent := (i - 1) / 2
		if h.a[parent] <= h.a[i] {
			break
		}
		h.a[parent], h.a[i] = h.a[i], h.a[parent]
		i = parent
	}
}

func (h *MinHeap) Pop() int {
	a := h.a
	top := a[0]
	n := len(a) - 1
	a[0] = a[n]
	a = a[:n]
	i := 0
	for { // sift down
		left, right, smallest := 2*i+1, 2*i+2, i
		if left < n && a[left] < a[smallest] {
			smallest = left
		}
		if right < n && a[right] < a[smallest] {
			smallest = right
		}
		if smallest == i {
			break
		}
		a[i], a[smallest] = a[smallest], a[i]
		i = smallest
	}
	h.a = a
	return top
}

func main() {
	h := &MinHeap{}
	for _, x := range []int{5, 3, 8, 1, 9, 2} {
		h.Push(x)
	}
	fmt.Println(h.a) // [1 3 2 5 9 8]
	var sorted []int
	for h.Len() > 0 {
		sorted = append(sorted, h.Pop())
	}
	fmt.Println(sorted) // [1 2 3 5 8 9]
}
#include <iostream>
#include <utility>
#include <vector>

class MinHeap {
public:
    std::vector<int> a;

    bool empty() const { return a.empty(); }

    void push(int x) {
        a.push_back(x);
        size_t i = a.size() - 1;
        while (i > 0) {                          // sift up
            size_t parent = (i - 1) / 2;
            if (a[parent] <= a[i]) break;
            std::swap(a[parent], a[i]);
            i = parent;
        }
    }

    int pop() {
        int top = a[0];
        a[0] = a.back();
        a.pop_back();
        size_t i = 0, n = a.size();
        while (true) {                           // sift down
            size_t left = 2 * i + 1, right = 2 * i + 2, smallest = i;
            if (left < n && a[left] < a[smallest]) smallest = left;
            if (right < n && a[right] < a[smallest]) smallest = right;
            if (smallest == i) break;
            std::swap(a[i], a[smallest]);
            i = smallest;
        }
        return top;
    }
};

int main() {
    MinHeap h;
    for (int x : {5, 3, 8, 1, 9, 2}) h.push(x);
    for (int x : h.a) std::cout << x << ' ';     // 1 3 2 5 9 8
    std::cout << '\n';
    while (!h.empty()) std::cout << h.pop() << ' '; // 1 2 3 5 8 9
    std::cout << '\n';
}

LeetCode 练习题

用到这一算法的经典题目,适合在玩过本实验室后动手练习。链接将打开力扣(LeetCode 中国)。

复杂度

  • 查看堆顶:O(1)。插入和取出:O(log n),只走一条根到叶的路径。
  • 自底向上建堆:O(n),因为大多数节点都靠近底部,只需下沉很短的距离。
  • 堆排序:任何情况下都是 O(n log n),原地排序,但不稳定。

堆的用途

调度器和事件模拟按优先级挑选下一个任务;Dijkstra 和 Prim 算法每次弹出最近的顶点;Top-K 查询维护一个大小为 k 的堆;合并 k 个有序文件时用堆保存各文件当前的队首。多数语言都内置了堆:Python heapq、Java PriorityQueue、C++ std::priority_queue。

常见问题

解答您关心的工具使用与数据安全相关问题。

为什么用数组而不是节点加指针?

堆永远是完全二叉树,没有空洞;用下标计算代替指针,更省内存,也更利于 CPU 缓存。

能在堆里快速查找吗?

不能,查找任意值需要 O(n)。如果需要有序查找,请使用平衡搜索树。

为什么建堆是 O(n) 而不是 O(n log n)?

下沉的代价取决于节点下方的高度。一半节点是叶子(代价 0),四分之一高度为 1,依此类推,总和收敛到约 2n。

使用该工具时我的数据安全吗?

绝对安全。本工具采用 100% 纯客户端本地计算技术,所有数据与文件均在您的本机浏览器内存中处理,绝不上传到任何远程服务器。