heap

package
v0.0.0-...-7a9c835 Latest Latest
Warning

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

Go to latest
Published: May 7, 2024 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Example (PriorityQueue)
package main

import (
	"fmt"
)

type Item struct {
	value    string
	priority int

	index int
}

type PriorityQueue []*Item

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

func (pq PriorityQueue) Less(i, j int) bool {

	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 *Item) {
	n := len(*pq)
	x.index = n
	*pq = append(*pq, x)
}

func (pq *PriorityQueue) Pop() *Item {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil
	item.index = -1
	*pq = old[0 : n-1]
	return item
}

func (pq *PriorityQueue) update(item *Item, value string, priority int) {
	item.value = value
	item.priority = priority
	Fix[*Item](pq, item.index)
}

func main() {
	items := map[string]int{
		"banana": 3, "apple": 2, "pear": 4,
	}

	pq := make(PriorityQueue, len(items))
	i := 0
	for value, priority := range items {
		pq[i] = &Item{
			value:    value,
			priority: priority,
			index:    i,
		}
		i++
	}
	Init[*Item](&pq)

	item := &Item{
		value:    "orange",
		priority: 1,
	}
	Push[*Item](&pq, item)
	pq.update(item, item.value, 5)

	for pq.Len() > 0 {
		item := Pop[*Item](&pq)
		fmt.Printf("%.2d:%s ", item.priority, item.value)
	}
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Fix

func Fix[T any](h Interface[T], i int)

func Init

func Init[T any](h Interface[T])

func Pop

func Pop[T any](h Interface[T]) T

func Push

func Push[T any](h Interface[T], x T)

func Remove

func Remove[T any](h Interface[T], i int) T

Types

type Interface

type Interface[T any] interface {
	sort.Interface
	Push(x T)
	Pop() T
}

type MaxHeap

type MaxHeap[T constraints.Ordered] []T

func (MaxHeap[T]) Len

func (h MaxHeap[T]) Len() int

func (MaxHeap[T]) Less

func (h MaxHeap[T]) Less(i, j int) bool

func (*MaxHeap[T]) Pop

func (h *MaxHeap[T]) Pop() T

func (*MaxHeap[T]) Push

func (h *MaxHeap[T]) Push(x T)

func (MaxHeap[T]) Swap

func (h MaxHeap[T]) Swap(i, j int)

type MinHeap

type MinHeap[T constraints.Ordered] []T

func (MinHeap[T]) Len

func (h MinHeap[T]) Len() int

func (MinHeap[T]) Less

func (h MinHeap[T]) Less(i, j int) bool

func (*MinHeap[T]) Pop

func (h *MinHeap[T]) Pop() T

func (*MinHeap[T]) Push

func (h *MinHeap[T]) Push(x T)

func (MinHeap[T]) Swap

func (h MinHeap[T]) Swap(i, j int)

Jump to

Keyboard shortcuts

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