-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpqueue.go
More file actions
367 lines (321 loc) · 8.08 KB
/
pqueue.go
File metadata and controls
367 lines (321 loc) · 8.08 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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
// Package pqueue provides an intelligent priority queue and sorting library
// that automatically selects the best algorithm based on data characteristics.
package pqueue
import (
"fmt"
"reflect"
)
// PQueue represents an intelligent priority queue with adaptive sorting
type PQueue[T any] struct {
data []T
less func(T, T) bool
dataType DataType
size int
}
// DataType represents the type of data being sorted
type DataType int
const (
IntegerType DataType = iota
FloatType
StringType
SliceType
ArrayType
StructType
MapType
PointerType
InterfaceType
ChannelType
FuncType
GenericType
)
// SortStrategy represents the sorting algorithm to use
type SortStrategy int
const (
AutoStrategy SortStrategy = iota
RadixStrategy
CountingStrategy
InsertionStrategy
TimsortStrategy
IntrosortStrategy
MergeStrategy
QuickStrategy
)
// New creates a new PQueue with the given data and comparison function
func New[T any](data []T, less func(T, T) bool) *PQueue[T] {
pq := &PQueue[T]{
data: make([]T, len(data)),
less: less,
size: len(data),
}
copy(pq.data, data)
pq.dataType = inferDataType(data)
return pq
}
// NewInts creates a new PQueue for integers
func NewInts(data []int) *PQueue[int] {
return New(data, func(a, b int) bool { return a < b })
}
// NewFloats creates a new PQueue for floats
func NewFloats(data []float64) *PQueue[float64] {
return New(data, func(a, b float64) bool { return a < b })
}
// NewStrings creates a new PQueue for strings
func NewStrings(data []string) *PQueue[string] {
return New(data, func(a, b string) bool { return a < b })
}
// NewBytes creates a new PQueue for byte slices
func NewBytes(data [][]byte) *PQueue[[]byte] {
return New(data, func(a, b []byte) bool {
for i := 0; i < len(a) && i < len(b); i++ {
if a[i] != b[i] {
return a[i] < b[i]
}
}
return len(a) < len(b)
})
}
// NewRunes creates a new PQueue for rune slices
func NewRunes(data [][]rune) *PQueue[[]rune] {
return New(data, func(a, b []rune) bool {
for i := 0; i < len(a) && i < len(b); i++ {
if a[i] != b[i] {
return a[i] < b[i]
}
}
return len(a) < len(b)
})
}
// NewComparable creates a new PQueue for any comparable type
func NewComparable[T comparable](data []T, less func(T, T) bool) *PQueue[T] {
return New(data, less)
}
// Comparable interface for types that can be compared
type Comparable interface {
CompareTo(other interface{}) int
}
// NewWithComparable creates a PQueue for types that implement Comparable
func NewWithComparable[T Comparable](data []T) *PQueue[T] {
return New(data, func(a, b T) bool {
return a.CompareTo(b) < 0
})
}
// Size returns the number of elements in the queue
func (pq *PQueue[T]) Size() int {
return pq.size
}
// IsEmpty returns true if the queue is empty
func (pq *PQueue[T]) IsEmpty() bool {
return pq.size == 0
}
// Push adds an element to the queue
func (pq *PQueue[T]) Push(item T) {
if pq.size >= len(pq.data) {
// Grow the slice
newSize := len(pq.data) * 2
if newSize == 0 {
newSize = 1 // Start with size 1 if empty
}
newData := make([]T, newSize)
copy(newData, pq.data[:pq.size])
pq.data = newData
}
pq.data[pq.size] = item
pq.size++
}
// Pop removes and returns the smallest element
func (pq *PQueue[T]) Pop() (T, error) {
var zero T
if pq.size == 0 {
return zero, fmt.Errorf("queue is empty")
}
// Find minimum element
minIdx := 0
for i := 1; i < pq.size; i++ {
if pq.less(pq.data[i], pq.data[minIdx]) {
minIdx = i
}
}
result := pq.data[minIdx]
// Move last element to the position of removed element
pq.data[minIdx] = pq.data[pq.size-1]
pq.size--
return result, nil
}
// Peek returns the smallest element without removing it
func (pq *PQueue[T]) Peek() (T, error) {
var zero T
if pq.size == 0 {
return zero, fmt.Errorf("queue is empty")
}
minIdx := 0
for i := 1; i < pq.size; i++ {
if pq.less(pq.data[i], pq.data[minIdx]) {
minIdx = i
}
}
return pq.data[minIdx], nil
}
// Sort sorts the queue using the optimal algorithm based on data characteristics
func (pq *PQueue[T]) Sort() {
pq.SortWithStrategy(AutoStrategy)
}
// SortWithStrategy sorts using a specific strategy
func (pq *PQueue[T]) SortWithStrategy(strategy SortStrategy) {
if pq.size <= 1 {
return
}
actualStrategy := strategy
if strategy == AutoStrategy {
actualStrategy = pq.chooseOptimalStrategy()
}
switch actualStrategy {
case InsertionStrategy:
pq.insertionSort()
case TimsortStrategy:
pq.timsort()
case IntrosortStrategy:
pq.introsort()
case MergeStrategy:
pq.mergeSort()
case QuickStrategy:
pq.quickSort()
case RadixStrategy:
if pq.dataType == IntegerType {
pq.radixSort()
} else {
pq.quickSort() // fallback
}
case CountingStrategy:
if pq.dataType == IntegerType {
pq.countingSort()
} else {
pq.quickSort() // fallback
}
default:
pq.quickSort()
}
}
// ToSlice returns a copy of the internal data
func (pq *PQueue[T]) ToSlice() []T {
result := make([]T, pq.size)
copy(result, pq.data[:pq.size])
return result
}
// GetDataType returns the inferred data type for debugging purposes
func (pq *PQueue[T]) GetDataType() DataType {
return pq.dataType
}
// GetDataTypeName returns a human-readable name for the data type
func (pq *PQueue[T]) GetDataTypeName() string {
switch pq.dataType {
case IntegerType:
return "Integer"
case FloatType:
return "Float"
case StringType:
return "String"
case SliceType:
return "Slice"
case ArrayType:
return "Array"
case StructType:
return "Struct"
case MapType:
return "Map"
case PointerType:
return "Pointer"
case InterfaceType:
return "Interface"
case ChannelType:
return "Channel"
case FuncType:
return "Function"
default:
return "Generic"
}
}
// inferDataType attempts to determine the data type using reflection
func inferDataType[T any](data []T) DataType {
if len(data) == 0 {
return GenericType
}
// Get the type of the first element
t := reflect.TypeOf(data[0])
// Handle pointers by getting the underlying type
if t.Kind() == reflect.Ptr {
return PointerType
}
switch t.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return IntegerType
case reflect.Float32, reflect.Float64:
return FloatType
case reflect.String:
return StringType
case reflect.Slice:
return SliceType
case reflect.Array:
return ArrayType
case reflect.Struct:
return StructType
case reflect.Map:
return MapType
case reflect.Interface:
return InterfaceType
case reflect.Chan:
return ChannelType
case reflect.Func:
return FuncType
default:
return GenericType
}
}
// chooseOptimalStrategy selects the best sorting algorithm based on data characteristics
func (pq *PQueue[T]) chooseOptimalStrategy() SortStrategy {
n := pq.size
// For very small arrays, use insertion sort
if n <= 16 {
return InsertionStrategy
}
// Check if data is nearly sorted
if pq.isNearlySorted() {
return InsertionStrategy
}
// For integer data with small range, use counting or radix sort
if pq.dataType == IntegerType && n > 100 {
if pq.hasSmallRange() {
return CountingStrategy
}
return RadixStrategy
}
// For strings, use specialized string sorting
if pq.dataType == StringType {
if n > 1000 {
return IntrosortStrategy // Good for large string datasets
}
return TimsortStrategy // Good for strings with patterns
}
// For slices and arrays, use stable sorting
if pq.dataType == SliceType || pq.dataType == ArrayType {
return MergeStrategy // Stable and predictable
}
// For structs and complex types, use comparison-based sorts
if pq.dataType == StructType || pq.dataType == InterfaceType {
if n > 1000 {
return IntrosortStrategy
}
return TimsortStrategy
}
// For pointers, maps, channels, functions - use generic approach
if pq.dataType == PointerType || pq.dataType == MapType ||
pq.dataType == ChannelType || pq.dataType == FuncType {
return QuickStrategy // Simple and effective for these types
}
// For large datasets, use introsort (hybrid approach)
if n > 1000 {
return IntrosortStrategy
}
// Default to timsort for general purpose
return TimsortStrategy
}