# container/heap

`container/heap` 提供堆積（heap）演算法：讓你隨時以 O(log n) 的成本取出「目前最小（或最優先）」的元素，常用來實作優先佇列。

## 這個套件做什麼

堆積像是「永遠把最急的工作放最上面」的待辦清單。和每次都重新排序整份清單不同，堆積只維持一個較寬鬆的規則：父節點不大於子節點。這樣新增與取出都只要 O(log n)，而最小的元素永遠在索引 0。

典型用途：

- 優先佇列（priority queue）：工作排程、事件模擬，依優先度處理
- 從大量資料中找前 K 大或前 K 小
- 最短路徑演算法（Dijkstra）、合併多個已排序串列

`container/heap` 本身不存資料，它只提供演算法。你準備一個型別（通常是切片）並實作 `heap.Interface`，再用 `heap.Init`、`heap.Push`、`heap.Pop` 操作它。

和相近工具的差別：

| 工具 | 適合 |
| --- | --- |
| `container/heap` | 資料持續增減，每次只需要取出最小／最大的那個 |
| [`slices.Sort`](/pkg-slices) | 一次性排序全部資料 |
| `slices.Min`／`slices.Max` | 偶爾找一次最小／最大值 |

## 匯入

```go
import "container/heap"
```

## 常用 API

### heap.Interface

要使用堆積，型別必須實作 `heap.Interface`：也就是 `sort.Interface` 的三個方法（`Len`、`Less`、`Swap`），加上 `Push` 與 `Pop`。

- `Less(i, j)` 決定誰在上面：用 `<` 是最小堆積（min-heap），用 `>` 就是最大堆積
- `Push(x)` 把 `x` 加到切片尾端
- `Pop()` 移除並回傳切片的最後一個元素

`Push` 與 `Pop` 要用指標接收者，因為它們會改變切片長度（觀念見 [指標接收者](/methods-pointer-receiver)）。

注意：型別上的 `Push`／`Pop` 方法是給 `heap` 套件內部呼叫的。你自己操作時要呼叫套件函式 `heap.Push(h, x)`、`heap.Pop(h)`，直接呼叫方法會破壞堆積的順序。

簽名：

```go
type Interface interface {
	sort.Interface
	Push(x any)
	Pop() any
}
```

範例：

```go
package main

import (
	"container/heap"
	"fmt"
)

type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *IntHeap) Push(x any) {
	*h = append(*h, x.(int))
}

func (h *IntHeap) Pop() any {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[:n-1]
	return x
}

func main() {
	h := &IntHeap{5, 2, 8}
	heap.Init(h)
	fmt.Println("min:", (*h)[0])

	var _ heap.Interface = h
	fmt.Println("len:", h.Len())
}
```

輸出：

```text
min: 2
len: 3
```

### Init

把一個任意順序的集合整理成合法的堆積，成本 O(n)。已經有一批資料時先呼叫 `Init`，之後再用 `Push`、`Pop`。空集合可以不呼叫。

簽名：

```go
func Init(h Interface)
```

範例：

```go
package main

import (
	"container/heap"
	"fmt"
)

type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x any)        { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() any {
	old := *h
	x := old[len(old)-1]
	*h = old[:len(old)-1]
	return x
}

func main() {
	h := &IntHeap{9, 4, 7, 1, 8}
	fmt.Println("before:", *h)
	heap.Init(h)
	fmt.Println("after: ", *h)
	fmt.Println("min:   ", (*h)[0])
}
```

輸出：

```text
before: [9 4 7 1 8]
after:  [1 4 7 9 8]
min:    1
```

`Init` 之後切片不是完全排序，只保證最小值在最前面、父節點不大於子節點。

### Push 與 Pop

`heap.Push` 加入一個元素並維持堆積規則；`heap.Pop` 移除並回傳最小的元素。兩者都是 O(log n)。不斷 `Pop` 直到空，就會依序得到由小到大的結果。

`Pop` 回傳 `any`，取出後要用型別斷言轉回原本型別（見 [型別斷言與型別 switch](/interfaces-type-assertion-switch)）。

注意：對空堆積呼叫 `heap.Pop` 會在你的 `Pop` 方法裡索引越界而 panic，呼叫前先檢查 `Len() > 0`。

簽名：

```go
func Push(h Interface, x any)
func Pop(h Interface) any
```

範例：

```go
package main

import (
	"container/heap"
	"fmt"
)

type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x any)        { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() any {
	old := *h
	x := old[len(old)-1]
	*h = old[:len(old)-1]
	return x
}

func main() {
	h := &IntHeap{}
	for _, n := range []int{5, 1, 9, 3} {
		heap.Push(h, n)
	}
	heap.Push(h, 0)

	for h.Len() > 0 {
		fmt.Print(heap.Pop(h).(int), " ")
	}
	fmt.Println()
}
```

輸出：

```text
0 1 3 5 9 
```

### 優先佇列與 Fix

實務上堆積裡放的通常是結構體，例如「工作名稱 + 優先度」。如果某個元素的優先度在加入之後改變，呼叫 `heap.Fix(h, i)` 讓它移到正確位置，比先移除再加入更有效率。

要知道元素目前在哪個索引，常見做法是在結構體裡存一個 `index` 欄位，並在 `Swap` 與 `Push` 時更新它。下面的範例用最大堆積（`Less` 用 `>`），優先度高的先處理。

簽名：

```go
func Fix(h Interface, i int)
```

範例：

```go
package main

import (
	"container/heap"
	"fmt"
)

type Task struct {
	Name     string
	Priority int
	index    int
}

type TaskQueue []*Task

func (q TaskQueue) Len() int           { return len(q) }
func (q TaskQueue) Less(i, j int) bool { return q[i].Priority > q[j].Priority }
func (q TaskQueue) Swap(i, j int) {
	q[i], q[j] = q[j], q[i]
	q[i].index = i
	q[j].index = j
}

func (q *TaskQueue) Push(x any) {
	t := x.(*Task)
	t.index = len(*q)
	*q = append(*q, t)
}

func (q *TaskQueue) Pop() any {
	old := *q
	n := len(old)
	t := old[n-1]
	old[n-1] = nil
	t.index = -1
	*q = old[:n-1]
	return t
}

func main() {
	q := &TaskQueue{}
	backup := &Task{Name: "backup", Priority: 1}
	heap.Push(q, &Task{Name: "email", Priority: 3})
	heap.Push(q, backup)
	heap.Push(q, &Task{Name: "deploy", Priority: 5})

	backup.Priority = 10
	heap.Fix(q, backup.index)

	for q.Len() > 0 {
		t := heap.Pop(q).(*Task)
		fmt.Printf("%s (priority %d)\n", t.Name, t.Priority)
	}
}
```

輸出：

```text
backup (priority 10)
deploy (priority 5)
email (priority 3)
```

`Pop` 中把 `old[n-1]` 設成 `nil`，是為了讓被取出的元素不再被底層陣列引用，可以被垃圾回收。

### Remove

移除並回傳索引 `i` 的元素，成本 O(log n)。用在「取消某個尚未處理的工作」這類情境。

注意：`i` 必須是有效索引（`0 <= i < Len()`），否則會 panic。

簽名：

```go
func Remove(h Interface, i int) any
```

範例：

```go
package main

import (
	"container/heap"
	"fmt"
	"slices"
)

type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x any)        { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() any {
	old := *h
	x := old[len(old)-1]
	*h = old[:len(old)-1]
	return x
}

func main() {
	h := &IntHeap{4, 8, 1, 6, 3}
	heap.Init(h)

	i := slices.Index(*h, 6)
	removed := heap.Remove(h, i)
	fmt.Println("removed:", removed)

	for h.Len() > 0 {
		fmt.Print(heap.Pop(h), " ")
	}
	fmt.Println()
}
```

輸出：

```text
removed: 6
1 3 4 8 
```

### 找出前 K 大

一個常見技巧：維持一個大小為 K 的最小堆積。每讀到一個新值就 `Push`，堆積超過 K 個時 `Pop` 掉最小的；全部讀完後，堆積裡剩下的就是最大的 K 個。記憶體只用 O(K)，適合資料量很大或資料是串流進來的情況。

範例：

```go
package main

import (
	"container/heap"
	"fmt"
	"slices"
)

type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x any)        { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() any {
	old := *h
	x := old[len(old)-1]
	*h = old[:len(old)-1]
	return x
}

func topK(nums []int, k int) []int {
	h := &IntHeap{}
	for _, n := range nums {
		heap.Push(h, n)
		if h.Len() > k {
			heap.Pop(h)
		}
	}
	result := slices.Clone(*h)
	slices.Sort(result)
	slices.Reverse(result)
	return result
}

func main() {
	scores := []int{55, 92, 13, 78, 92, 41, 88, 67}
	fmt.Println(topK(scores, 3))
}
```

輸出：

```text
[92 92 88]
```

## 重點整理

- `container/heap` 只提供演算法，資料結構由你實作 `heap.Interface`（`sort.Interface` + `Push` + `Pop`）
- `Less` 用 `<` 是最小堆積、用 `>` 是最大堆積；索引 0 永遠是最優先的元素
- 操作時呼叫套件函式 `heap.Push`／`heap.Pop`，不要直接呼叫型別上的方法
- 元素優先度改變後用 `heap.Fix`；取消元素用 `heap.Remove`
- 對空堆積 `Pop` 會 panic，先檢查 `Len()`

## 資料來源

- [dsxwk/go-docs（標準庫分類架構參考）](https://github.com/dsxwk/go-docs)
- [pkg.go.dev：container/heap](https://pkg.go.dev/container/heap)
- [Go 1.26.0 原始碼：src/container/heap](https://github.com/golang/go/tree/go1.26.0/src/container/heap)
