...

Package goheap

import "github.com/otaviog/goheap"
Overview
Index

Overview ▾

goheap is a simple implementation of the heap data structure and sorting algorithm. Its intention is for learning purposes of the Go language.

func HeapSort

func HeapSort[T constraints.Ordered](slice []T)

Sorts a slice in increasing order. Its time complexity is O(N log N) where N is the size of the slice.

type Heap

Generic heap structure

type Heap[T any] struct {
    // contains filtered or unexported fields
}

func MakeHeap

func MakeHeap[T any](slice []T, lessFunc func(lfs, rhs T) bool) Heap[T]

Makes an existing slice an Heap ordered according to the lessFunc function.

func New

func New[T any](lessFunc func(lfs, rhs T) bool, values ...T) *Heap[T]

Creates a new heap data structure ordered by the lesser function lessFunc and with optional starting values.

func (Heap[T]) Capacity

func (obj Heap[T]) Capacity() int

The current capacity to store elements.

func (*Heap[T]) Insert

func (heap *Heap[T]) Insert(value T)

Inserts a value into the heap. If its internal slice is full then it will append the element which breaks the pointer to the old slice. Its time complexity is O(log N) swaps where N is the heap size.

func (Heap[T]) Len

func (obj Heap[T]) Len() int

The number of elements inside the heap.

func (*Heap[T]) Remove

func (heap *Heap[T]) Remove() (removedValue T, err error)

Remove the lesser value from the heap, example:

heap := MakeHeap([]int{8, 9, 4, 2, 7}, func(a, b int) bool { return a < b })
value, _ := heap.Remove()
value, _ := heap.Remove()

It should output 2 and 4. If the heap is empty, then returns an error. Its time complexity is O(log N) where N is the heap size.