Skip to content

fsmiamoto/heap

Repository files navigation

heap

go.dev reference Go Report Card GoCover Test

A generic binary heap data structure in Go.

It works with any type as long as you provide a comparison function.

The package defines two example functions for building a Max or Min Heap of integers.

Examples

  • Heapsort
func main() {
    values := []interface{}{40, 30, 50, 100, 15}

    // You can specify an initial capacity for the heap,
    // len(values) in this case, which helps to avoid reallocations.
    // Also, this heap uses the package defined MinInt comparison function,
    // that builds a MinHeap of integers
    h := heap.New(values, len(values), heap.MinInt)

    var sorted []int
    for !h.IsEmpty() {
        v, err := h.Extract()
        if err != nil {
            log.Fatal(err)
        }
        sorted = append(sorted, v.(int))
    }
    fmt.Println(sorted) // [15 30 40 50 100]
}

About

A generic binary heap implementation in Go

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages