Fix Heap Order After Priority Updates

Keep container/heap ordering after a priority change by tracking each element index and calling heap.Fix, then drop an item from the middle with heap.Remove.

GoResilience

Code

gosnippet
63 lines
package main

import (
	"container/heap"
	"fmt"
)

type Task struct {
	name     string
	priority int
	index    int // 堆中位置:heap.Fix / heap.Remove 靠它定位元素
}

type Queue []*Task

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

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

func (q *Queue) 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 := &Queue{}
	heap.Init(q)

	alpha := &Task{name: "alpha", priority: 2}
	beta := &Task{name: "beta", priority: 5}
	heap.Push(q, alpha)
	heap.Push(q, beta)
	heap.Push(q, &Task{name: "gamma", priority: 1})
	fmt.Println("top:", (*q)[0].name)

	// 改了字段就等于改了排序键:原地修复,不必 Pop 再 Push
	alpha.priority = 9
	heap.Fix(q, alpha.index)
	fmt.Println("top after fix:", (*q)[0].name)

	// 取消中间元素:heap.Remove 用它当前的 index 直接摘掉
	heap.Remove(q, beta.index)

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

What happens as it runs

Everything happens inside the functions Len, Less, Swap and Push.

The one repetition in this snippet is the loop for q.Len() > 0.

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

The declaration to build on: func (q Queue) Len() int

Each print marks its step: top: shows the head before any repair (beta, priority 5), top after fix: shows the head once alpha.priority = 9 has been re-heapified, and the trailing pop lines drain what is left in descending priority.

Running the file executes main, which drives Push, Len and Pop in order.

Key statements

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

Interactive Tools for This Topic

FAQ

What does Fix Heap Order After Priority Updates print when run?
Execute the whole file; each printed line is prefixed with a label like `top:`, `top after fix:`, `pop`.