Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more generic way to implement 2 kinds of Heap (Max and Min) in Go Lang

Tags:

go

Currently, the example on Go lang doc is like this:

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
}

I really don't want to repeat myself creating a set of methods for Min Heap and another set of methods for Max Heap. Is there a better way?

like image 534
knd Avatar asked May 10 '14 11:05

knd


People also ask

Can you build a min/max heap in linear time?

Like binary min-heaps and max-heaps, min-max heaps support logarithmic insertion and deletion and can be built in linear time.

How do I declare min heap and max heap?

In a Min-Heap the key present at the root node must be less than or equal to among the keys present at all of its children. In a Max-Heap the key present at the root node must be greater than or equal to among the keys present at all of its children. 2. In a Min-Heap the minimum key element present at the root.

Can heap have more than 2 children?

The maximum number of children each node can have depends on the type of heap, but in many types it is at most two, which is known as a binary heap.


1 Answers

You can create a max heap from your min heap using embedding, like this

type MaxHeap struct {
    IntHeap
}

func (h MaxHeap) Less(i, j int) bool { return h.IntHeap[i] > h.IntHeap[j] }

See the playground for a working example.

like image 100
Nick Craig-Wood Avatar answered Oct 28 '22 10:10

Nick Craig-Wood