Repository navigation
Expand file tree
/
Copy pathpriorityqueue.go
More file actions
300 lines (270 loc) · 8.62 KB
/
Copy pathpriorityqueue.go
File metadata and controls
300 lines (270 loc) · 8.62 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package collections
import (
"bytes"
"encoding/gob"
"encoding/json"
"encoding/json/jsontext"
jsonv2 "encoding/json/v2"
"errors"
"iter"
"slices"
)
// priorityQueue is a heap-based implementation of PriorityQueue[T].
// - O(log n) push and pop
// - O(1) peek
// - By default, smallest element has highest priority (min-heap)
// - Use a reverse comparator for max-heap behavior.
type priorityQueue[T any] struct {
data []T
cmp Comparator[T]
}
// siftUp moves the element at index i toward the root until the heap
// invariant holds. O(log n).
func (pq *priorityQueue[T]) siftUp(i int) {
for i > 0 {
parent := (i - 1) / 2
if pq.cmp(pq.data[i], pq.data[parent]) >= 0 {
return
}
pq.data[i], pq.data[parent] = pq.data[parent], pq.data[i]
i = parent
}
}
// siftDown moves the element at index i toward the leaves until the heap
// invariant holds. O(log n).
func (pq *priorityQueue[T]) siftDown(i int) {
n := len(pq.data)
for {
left := 2*i + 1
if left >= n {
return
}
smallest := left
if right := left + 1; right < n && pq.cmp(pq.data[right], pq.data[left]) < 0 {
smallest = right
}
if pq.cmp(pq.data[smallest], pq.data[i]) >= 0 {
return
}
pq.data[i], pq.data[smallest] = pq.data[smallest], pq.data[i]
i = smallest
}
}
// heapify re-establishes the heap invariant over the whole backing slice. O(n).
func (pq *priorityQueue[T]) heapify() {
for i := len(pq.data)/2 - 1; i >= 0; i-- {
pq.siftDown(i)
}
}
// NewPriorityQueue creates an empty priority queue with a custom comparator.
// The comparator determines priority: elements with smaller comparison values
// have higher priority (min-heap). Use a reverse comparator for max-heap.
func NewPriorityQueue[T any](cmp Comparator[T]) PriorityQueue[T] {
if cmp == nil {
panic("NewPriorityQueue: comparator must not be nil")
}
return newPriorityQueue(cmp)
}
// newPriorityQueue creates the concrete queue for internal callers.
func newPriorityQueue[T any](cmp Comparator[T]) *priorityQueue[T] {
return &priorityQueue[T]{
data: make([]T, 0),
cmp: cmp,
}
}
// NewPriorityQueueOrdered creates a min-heap priority queue for Ordered types.
// Smallest element has highest priority.
func NewPriorityQueueOrdered[T Ordered]() PriorityQueue[T] {
return NewPriorityQueue(CompareFunc[T]())
}
// NewPriorityQueueWithCapacity creates a priority queue with capacity hint.
func NewPriorityQueueWithCapacity[T any](cmp Comparator[T], capacity int) PriorityQueue[T] {
if cmp == nil {
panic("NewPriorityQueueWithCapacity: comparator must not be nil")
}
if capacity < 0 {
capacity = 0
}
return &priorityQueue[T]{
data: make([]T, 0, capacity),
cmp: cmp,
}
}
// NewPriorityQueueFrom creates a priority queue from elements.
func NewPriorityQueueFrom[T any](cmp Comparator[T], elements ...T) PriorityQueue[T] {
if cmp == nil {
panic("NewPriorityQueueFrom: comparator must not be nil")
}
pq := &priorityQueue[T]{
data: make([]T, len(elements)),
cmp: cmp,
}
copy(pq.data, elements)
pq.heapify()
return pq
}
// NewMaxPriorityQueue creates a max-heap priority queue for Ordered types.
// Largest element has highest priority.
func NewMaxPriorityQueue[T Ordered]() PriorityQueue[T] {
c := CompareFunc[T]()
return NewPriorityQueue(func(a, b T) int {
return c(b, a) // Reverse comparison
})
}
// Size returns the number of elements.
func (pq *priorityQueue[T]) Size() int { return len(pq.data) }
// IsEmpty reports whether the queue is empty.
func (pq *priorityQueue[T]) IsEmpty() bool { return len(pq.data) == 0 }
func (pq *priorityQueue[T]) IsNotEmpty() bool { return !pq.IsEmpty() }
// Clear removes all elements (retains capacity).
func (pq *priorityQueue[T]) Clear() {
clear(pq.data)
pq.data = pq.data[:0]
}
// String returns a concise representation.
func (pq *priorityQueue[T]) String() string {
return formatCollection("priorityQueue", pq.Seq())
}
// Push adds an element to the queue. O(log n).
func (pq *priorityQueue[T]) Push(element T) {
pq.data = append(pq.data, element)
pq.siftUp(len(pq.data) - 1)
}
// PushAll adds all elements to the queue.
func (pq *priorityQueue[T]) PushAll(elements ...T) {
if len(elements) == 0 {
return
}
// For batches comparable to the heap size, one O(n+m) heapify beats
// m separate O(log n) sift-ups.
if len(elements) >= len(pq.data) {
pq.data = append(pq.data, elements...)
pq.heapify()
return
}
for _, e := range elements {
pq.Push(e)
}
}
// Pop removes and returns the highest-priority element, or (zero, false) if empty. O(log n).
func (pq *priorityQueue[T]) Pop() (T, bool) {
if len(pq.data) == 0 {
var zero T
return zero, false
}
v := pq.data[0]
n := len(pq.data) - 1
pq.data[0] = pq.data[n]
// Clear the vacated slot to drop references promptly.
var zero T
pq.data[n] = zero
pq.data = pq.data[:n]
pq.siftDown(0)
return v, true
}
// Peek returns the highest-priority element without removing it, or (zero, false) if empty. O(1).
func (pq *priorityQueue[T]) Peek() (T, bool) {
if len(pq.data) == 0 {
var zero T
return zero, false
}
return pq.data[0], true
}
// ToSlice returns elements in heap order (not sorted).
func (pq *priorityQueue[T]) ToSlice() []T {
return slices.Clone(pq.data)
}
// ToSortedSlice returns elements in priority order (sorted).
func (pq *priorityQueue[T]) ToSortedSlice() []T {
out := slices.Clone(pq.data)
slices.SortFunc(out, pq.cmp)
return out
}
// Seq returns a sequence in heap order (not sorted).
func (pq *priorityQueue[T]) Seq() iter.Seq[T] {
return slices.Values(pq.data)
}
// ==========================
// Serialization
// ==========================
// MarshalJSON implements json.Marshaler.
// Serializes elements in heap order (not sorted).
//
// NOTE: The comparator is NOT serialized. Decode into a queue constructed
// with NewPriorityQueue, or use UnmarshalPriorityQueueJSON /
// UnmarshalPriorityQueueOrderedJSON.
func (pq *priorityQueue[T]) MarshalJSON() ([]byte, error) {
return json.Marshal(pq.data)
}
// UnmarshalJSON implements json.Unmarshaler.
// Deserializes into the receiver using its existing comparator, so construct
// the queue with NewPriorityQueue (or a helper) before decoding.
func (pq *priorityQueue[T]) UnmarshalJSON(data []byte) error {
if pq.cmp == nil {
return errors.New("unmarshal priorityqueue: no comparator; construct the queue with NewPriorityQueue before decoding, or use UnmarshalPriorityQueueJSON/UnmarshalPriorityQueueOrderedJSON")
}
var elements []T
if err := json.Unmarshal(data, &elements); err != nil {
return err
}
pq.data = elements
// Re-establish the heap invariant: the source need not be heap-ordered.
pq.heapify()
return nil
}
// MarshalJSONTo implements jsonv2.MarshalerTo.
// Streams the same JSON as MarshalJSON into enc.
func (pq *priorityQueue[T]) MarshalJSONTo(enc *jsontext.Encoder) error {
return jsonv2.MarshalEncode(enc, pq.data)
}
// UnmarshalJSONFrom implements jsonv2.UnmarshalerFrom.
// Accepts the same JSON as UnmarshalJSON, streamed from dec.
// Same comparator contract as UnmarshalJSON.
func (pq *priorityQueue[T]) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
if pq.cmp == nil {
return errors.New("unmarshal priorityqueue: no comparator; construct the queue with NewPriorityQueue before decoding, or use UnmarshalPriorityQueueJSON/UnmarshalPriorityQueueOrderedJSON")
}
var elements []T
if err := jsonv2.UnmarshalDecode(dec, &elements); err != nil {
return err
}
pq.data = elements
// Re-establish the heap invariant: the source need not be heap-ordered.
pq.heapify()
return nil
}
// GobEncode implements gob.GobEncoder.
// Serializes elements in heap order (not sorted).
//
// NOTE: The comparator is NOT serialized. Decode into a queue constructed
// with NewPriorityQueue, or use UnmarshalPriorityQueueGob /
// UnmarshalPriorityQueueOrderedGob.
func (pq *priorityQueue[T]) GobEncode() ([]byte, error) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
if err := enc.Encode(pq.data); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// GobDecode implements gob.GobDecoder.
// Deserializes into the receiver using its existing comparator, so construct
// the queue with NewPriorityQueue (or a helper) before decoding.
func (pq *priorityQueue[T]) GobDecode(data []byte) error {
if pq.cmp == nil {
return errors.New("unmarshal priorityqueue: no comparator; construct the queue with NewPriorityQueue before decoding, or use UnmarshalPriorityQueueGob/UnmarshalPriorityQueueOrderedGob")
}
var elements []T
dec := gob.NewDecoder(bytes.NewReader(data))
if err := dec.Decode(&elements); err != nil {
return err
}
pq.data = elements
// Re-establish the heap invariant: the source need not be heap-ordered.
pq.heapify()
return nil
}
// Compile-time conformance.
var (
_ PriorityQueue[int] = (*priorityQueue[int])(nil)
)