互動實驗室在瀏覽器中執行

二元堆積與堆積排序

最大堆/最小堆雙視圖聯動演示,支援上浮、下沉與堆積排序全流程。

速度:
以陣列儲存的最大堆積:索引 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% 純客戶端本地計算技術,所有資料與檔案均在您的本機瀏覽器記憶體中處理,絕不上傳到任何伺服器。