Created
January 17, 2022 15:26
-
-
Save CollinShoop/4fff208e15eba47971352e4ab5de208d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func NewIntHeap(initialSize int, maxSize int, desc bool) *IntHeap { | |
return &IntHeap{ | |
data: make([]int, initialSize)[0:0], | |
desc: desc, | |
maxSize: maxSize, | |
} | |
} | |
type IntHeap struct { | |
data []int | |
desc bool // true = descending, false = ascending | |
initialSize int | |
maxSize int | |
} | |
func (h *IntHeap) resetData() { | |
h.data = make([]int, h.initialSize)[0:0] | |
heap.Init(h) | |
} | |
func (h IntHeap) Len() int { | |
return len(h.data) | |
} | |
func (h IntHeap) Less(i, j int) bool { | |
if h.desc { | |
return h.data[i] > h.data[j] | |
} | |
return h.data[i] < h.data[j] | |
} | |
func (h IntHeap) Swap(i, j int) { | |
h.data[i], h.data[j] = h.data[j], h.data[i] | |
} | |
func (h *IntHeap) Push(x interface{}) { | |
h.data = append(h.data, x.(int)) | |
} | |
func (h *IntHeap) Prune() { | |
if h.maxSize == 0 || h.Len() < h.maxSize { | |
return | |
} | |
// pop the desired values | |
r := make([]int, h.maxSize) | |
for i := 0; i < h.maxSize; i++ { | |
r[i] = heap.Pop(h).(int) | |
} | |
// reset heap data | |
h.resetData() | |
// push back | |
for _, v := range r { | |
heap.Push(h, v) | |
} | |
} | |
func (h *IntHeap) Pop() interface{} { | |
n := h.Len() | |
x := h.data[n-1] | |
h.data = h.data[0:n-1] | |
return x | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment