-
Notifications
You must be signed in to change notification settings - Fork 10
/
heap.go
80 lines (70 loc) · 1.3 KB
/
heap.go
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright (c) 2023 cheng-zhongliang. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package event
type eventHeap []*Event
func (eh eventHeap) less(i, j int) bool {
return eh[i].deadline.Before(eh[j].deadline)
}
func (eh eventHeap) swap(i, j int) {
eh[i], eh[j] = eh[j], eh[i]
eh[i].index = i
eh[j].index = j
}
func (eh eventHeap) up(j int) {
for {
i := (j - 1) / 4
if i == j || !eh.less(j, i) {
break
}
eh.swap(i, j)
j = i
}
}
func (eh eventHeap) down(i0, n int) bool {
i := i0
for {
j1 := 4*i + 1
if j1 >= n {
break
}
j := j1
if j2 := j1 + 1; j2 < n && eh.less(j2, j1) {
j = j2
}
if j3 := j1 + 2; j3 < n && eh.less(j3, j) {
j = j3
}
if j4 := j1 + 3; j4 < n && eh.less(j4, j) {
j = j4
}
if !eh.less(j, i) {
break
}
eh.swap(i, j)
i = j
}
return i > i0
}
func (eh *eventHeap) pushEvent(ev *Event) int {
*eh = append(*eh, ev)
ev.index = len(*eh) - 1
eh.up(ev.index)
return ev.index
}
func (eh *eventHeap) removeEvent(index int) {
n := len(*eh) - 1
if n != index {
eh.swap(index, n)
if !eh.down(index, n) {
eh.up(index)
}
}
*eh = (*eh)[:n]
}
func (eh *eventHeap) peekEvent() *Event {
return (*eh)[0]
}
func (eh *eventHeap) empty() bool {
return len(*eh) == 0
}