Sobes.tech
Senior

What is a heap as a data structure?

sobes.tech AI

Answer from AI

A heap is a specialized data structure, usually implemented as a binary tree, that satisfies the heap property: the value in each node is greater (for max-heap) or less (for min-heap) than the values of its children. This allows for quick retrieval of the maximum or minimum element.

Main characteristics:

  • Fast insertion and removal of the root element (usually in O(log n)).
  • Used to implement priority queues.

Example of a min-heap:

package main
import (
	"container/heap"
	"fmt"
)

// IntHeap implements a min-heap for integers
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{}) {
	*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
}

func main() {
	h := &IntHeap{2, 1, 5}
	heap.Init(h)
	heap.Push(h, 3)
	fmt.Printf("min: %d\n", (*h)[0])
	for h.Len() > 0 {
		fmt.Printf("%d ", heap.Pop(h))
	}
}