@@ -45,9 +45,20 @@ func NewWithStringComparator() *Heap {
45
45
}
46
46
47
47
// Push adds a value onto the heap and bubbles it up accordingly.
48
- func (heap * Heap ) Push (value interface {}) {
49
- heap .list .Add (value )
50
- heap .bubbleUp ()
48
+ func (heap * Heap ) Push (values ... interface {}) {
49
+ if len (values ) == 1 {
50
+ heap .list .Add (values [0 ])
51
+ heap .bubbleUp ()
52
+ } else {
53
+ // Reference: https://en.wikipedia.org/wiki/Binary_heap#Building_a_heap
54
+ for _ , value := range values {
55
+ heap .list .Add (value )
56
+ }
57
+ size := heap .list .Size ()/ 2 + 1
58
+ for i := size ; i >= 0 ; i -- {
59
+ heap .bubbleDownIndex (i )
60
+ }
61
+ }
51
62
}
52
63
53
64
// Pop removes top element on heap and returns it, or nil if heap is empty.
@@ -101,10 +112,15 @@ func (heap *Heap) String() string {
101
112
return str
102
113
}
103
114
104
- // Performs the "bubble down" operation. This is to place the element that is at the
105
- // root of the heap in its correct place so that the heap maintains the min/max-heap order property.
115
+ // Performs the "bubble down" operation. This is to place the element that is at the root
116
+ // of the heap in its correct place so that the heap maintains the min/max-heap order property.
106
117
func (heap * Heap ) bubbleDown () {
107
- index := 0
118
+ heap .bubbleDownIndex (0 )
119
+ }
120
+
121
+ // Performs the "bubble down" operation. This is to place the element that is at the index
122
+ // of the heap in its correct place so that the heap maintains the min/max-heap order property.
123
+ func (heap * Heap ) bubbleDownIndex (index int ) {
108
124
size := heap .list .Size ()
109
125
for leftIndex := index << 1 + 1 ; leftIndex < size ; leftIndex = index << 1 + 1 {
110
126
rightIndex := index << 1 + 2
0 commit comments