-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap.go
More file actions
39 lines (31 loc) · 718 Bytes
/
heap.go
File metadata and controls
39 lines (31 loc) · 718 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package sampling
type Node struct {
Key float64
Obj interface{}
}
// MinHeap implements a min heap based on Node.Key
// For weighted reservoir sampling, the Key is a relative weight to determine whether
// or not should be selected into the sample.
type MinHeap []*Node
func (h MinHeap) Len() int {
return len(h)
}
func (h MinHeap) Less(i, j int) bool {
return h[i].Key > h[j].Key
}
func (h MinHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
}
func (h *MinHeap) Push(x interface{}) {
*h = append(*h, x.(*Node))
}
func (h *MinHeap) Pop() interface{} {
curr := *h
size := len(curr)
*h = curr[0 : size-1]
min := curr[size-1]
return min
}
func (h *MinHeap) Peek() interface{} {
return (*h)[len(*h)-1]
}