heap

package
v0.0.15 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2024 License: BSD-3-Clause Imports: 6 Imported by: 0

Documentation

Overview

Example (IntHeap)

This example inserts several ints into an IntHeap, checks the minimum, and removes them in order of priority.

// This example demonstrates an integer heap built using the heap interface.
package main

import (
	"container/heap"
	"fmt"
)

// An IntHeap is a min-heap of ints.
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 interface{}) {
	// Push and Pop use pointer receivers because they modify the slice's length,
	// not just its contents.
	*h = append(*h, x.(int))
}

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

// This example inserts several ints into an IntHeap, checks the minimum,
// and removes them in order of priority.
func main() {
	h := &IntHeap{2, 1, 5}
	heap.Init(h)
	heap.Push(h, 3)
	fmt.Printf("minimum: %d\n", (*h)[0])
	for h.Len() > 0 {
		fmt.Printf("%d ", heap.Pop(h))
	}
}
Output:

minimum: 1
1 2 3 5
Example (PriorityQueue)

This example creates a PriorityQueue with some items, adds and manipulates an item, and then removes the items in priority order.

// This example demonstrates a priority queue built using the heap interface.
package main

import (
	"container/heap"
	"fmt"
)

// An Item is something we manage in a priority queue.
type Item struct {
	value    string // The value of the item; arbitrary.
	priority int    // The priority of the item in the queue.
	// The index is needed by update and is maintained by the heap.Interface methods.
	index int // The index of the item in the heap.
}

// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
	return pq[i].priority > pq[j].priority
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

// update modifies the priority and value of an Item in the queue.
func (pq *PriorityQueue) update(item *Item, value string, priority int) {
	item.value = value
	item.priority = priority
	heap.Fix(pq, item.index)
}

// This example creates a PriorityQueue with some items, adds and manipulates an item,
// and then removes the items in priority order.
func main() {
	// Some items and their priorities.
	items := map[string]int{
		"banana": 3, "apple": 2, "pear": 4,
	}

	// Create a priority queue, put the items in it, and
	// establish the priority queue (heap) invariants.
	pq := make(PriorityQueue, len(items))
	i := 0
	for value, priority := range items {
		pq[i] = &Item{
			value:    value,
			priority: priority,
			index:    i,
		}
		i++
	}
	heap.Init(&pq)

	// Insert a new item and then modify its priority.
	item := &Item{
		value:    "orange",
		priority: 1,
	}
	heap.Push(&pq, item)
	pq.update(item, item.value, 5)

	// Take the items out; they arrive in decreasing priority order.
	for pq.Len() > 0 {
		item := heap.Pop(&pq).(*Item)
		fmt.Printf("%.2d:%s ", item.priority, item.value)
	}
}
Output:

05:orange 04:pear 03:banana 02:apple

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Heap

type Heap[T comparable.Comparable] struct {
	// contains filtered or unexported fields
}

The heap data is stored in a slice of type *T

func NewHeap

func NewHeap[T comparable.Comparable]() *Heap[T]

Create a new heap and return it. Complexity is O(1).

func (*Heap[T]) AppendHeap

func (hp *Heap[T]) AppendHeap(x []*T)

AppendHeap appends a new set of data to the heap (and leaves the heap in a non-heap state). After 1..n AppendHeap operations a call to Heapify() is necessary to re-heap the heap.

Example: `h.Heapify(h.Len(),0)` will re-build the entire heap.

func (*Heap[T]) Delete

func (hp *Heap[T]) Delete(ii int) (rv *T)

Delete removes and returns the element at the specified index `ii` from the heap. Complexity is O(log n).

func (*Heap[T]) Dump added in v0.0.6

func (hp *Heap[T]) Dump(fp io.Writer)

func (*Heap[T]) Fix

func (hp *Heap[T]) Fix(ii int, newValue *T)

Fix re-establishes the heap ordering after a change to the value of the element at locaiton `ii`. Changing the value of the element (indrement/decrement/update) at `ii` followed by a call to Fix() is the same as hp.Delete(ii) and hp.Push(NewValue). It is less expesive to call use the Fix operation. Complexity is O(log n).

func (*Heap[T]) GetValue

func (hp *Heap[T]) GetValue(ii int) (value *T)

GetValue will return the value at index `ii` in the heap. Complexity is O(1).

func (*Heap[T]) Heapify

func (hp *Heap[T]) Heapify(n, i int)

xyzzzy- Commnet- To heapify a subtree rooted with node i which is an index in arr[]. N is size of heap Heapify starts at the sub-tree at 'i' and re-construts the heap. This is useful after an AppendHeap operation. `h.Heapify(h.Len(),0)` will re-build the entire heap.

func (*Heap[T]) Len

func (hp *Heap[T]) Len() int

Len will return the number of items in the heap. Complexity is O(1).

func (*Heap[T]) Length

func (hp *Heap[T]) Length() int

func (*Heap[T]) Peek

func (hp *Heap[T]) Peek() (rv *T)

func (*Heap[T]) Pop

func (hp *Heap[T]) Pop() (rv *T)

Pop removes and returns the minimum element (using comparable.Compare). Pop is the same as hp.Remove(0). Complexity is O(log n).

func (*Heap[T]) Push

func (hp *Heap[T]) Push(x *T)

Push appends the element x onto the end of the heap and re-orders the heap to be a heap. Complexity is O(log n).

func (*Heap[T]) Search

func (hp *Heap[T]) Search(cmpVal *T) (rv *T, pos int, err error)

Complexity is O(n).

func (*Heap[T]) SetValue

func (hp *Heap[T]) SetValue(ii int, newValue *T)

func (*Heap[T]) Truncate

func (hp *Heap[T]) Truncate()

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL