forked from MauriceGit/skiplist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathskiplist.go
620 lines (519 loc) · 15 KB
/
skiplist.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
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
// MIT License
//
// Copyright (c) 2018 Maurice Tollmien ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Package skiplist is an implementation of a skiplist to store elements in increasing order.
// It allows finding, insertion and deletion operations in approximately O(n log(n)).
// Additionally, there are methods for retrieving the next and previous element as well as changing the actual value
// without the need for re-insertion (as long as the key stays the same!)
// Skiplist is a fast alternative to a balanced tree.
package skiplist
import (
"fmt"
"math"
"math/bits"
"math/rand"
"time"
)
const (
// maxLevel denotes the maximum height of the skiplist. This height will keep the skiplist
// efficient for up to 34m entries. If there is a need for much more, please adjust this constant accordingly.
maxLevel = 25
eps = 0.00001
)
// ListElement is the interface to implement for elements that are inserted into the skiplist.
type ListElement interface {
// ExtractKey() returns a float64 representation of the key that is used for insertion/deletion/find. It needs to establish an order over all elements
ExtractKey() float64
// A string representation of the element. Can be used for pretty-printing the list. Otherwise just return an empty string.
String() string
}
// SkipListElement represents one actual Node in the skiplist structure.
// It saves the actual element, pointers to the next nodes and a pointer to one previous node.
type SkipListElement struct {
next [maxLevel]*SkipListElement
level int
key float64
value ListElement
prev *SkipListElement
}
// SkipList is the actual skiplist representation.
// It saves all nodes accessible from the start and end and keeps track of element count, eps and levels.
type SkipList struct {
startLevels [maxLevel]*SkipListElement
endLevels [maxLevel]*SkipListElement
maxNewLevel int
maxLevel int
elementCount int
eps float64
}
// NewSeedEps returns a new empty, initialized Skiplist.
// Given a seed, a deterministic height/list behaviour can be achieved.
// Eps is used to compare keys given by the ExtractKey() function on equality.
func NewSeedEps(seed int64, eps float64) SkipList {
// Initialize random number generator.
rand.Seed(seed)
//fmt.Printf("SkipList seed: %v\n", seed)
list := SkipList{
startLevels: [maxLevel]*SkipListElement{},
endLevels: [maxLevel]*SkipListElement{},
maxNewLevel: maxLevel,
maxLevel: 0,
elementCount: 0,
eps: eps,
}
return list
}
// NewEps returns a new empty, initialized Skiplist.
// Eps is used to compare keys given by the ExtractKey() function on equality.
func NewEps(eps float64) SkipList {
return NewSeedEps(time.Now().UTC().UnixNano(), eps)
}
// NewSeed returns a new empty, initialized Skiplist.
// Given a seed, a deterministic height/list behaviour can be achieved.
func NewSeed(seed int64) SkipList {
return NewSeedEps(seed, eps)
}
// New returns a new empty, initialized Skiplist.
func New() SkipList {
return NewSeedEps(time.Now().UTC().UnixNano(), eps)
}
// IsEmpty checks, if the skiplist is empty.
func (t *SkipList) IsEmpty() bool {
return t.startLevels[0] == nil
}
func (t *SkipList) generateLevel(maxLevel int) int {
level := maxLevel - 1
// First we apply some mask which makes sure that we don't get a level
// above our desired level. Then we find the first set bit.
var x uint64 = rand.Uint64() & ((1 << uint(maxLevel-1)) - 1)
zeroes := bits.TrailingZeros64(x)
if zeroes <= maxLevel {
level = zeroes
}
return level
}
func (t *SkipList) findEntryIndex(key float64, level int) int {
// Find good entry point so we don't accidentally skip half the list.
for i := t.maxLevel; i >= 0; i-- {
if t.startLevels[i] != nil && t.startLevels[i].key <= key || i <= level {
return i
}
}
return 0
}
func (t *SkipList) findExtended(key float64, findGreaterOrEqual bool) (foundElem *SkipListElement, ok bool) {
foundElem = nil
ok = false
if t.IsEmpty() {
return
}
index := t.findEntryIndex(key, 0)
var currentNode *SkipListElement
currentNode = t.startLevels[index]
nextNode := currentNode
// In case, that our first element is already greater-or-equal!
if findGreaterOrEqual && currentNode.key > key {
foundElem = currentNode
ok = true
return
}
for {
if math.Abs(currentNode.key-key) <= t.eps {
foundElem = currentNode
ok = true
return
}
nextNode = currentNode.next[index]
// Which direction are we continuing next time?
if nextNode != nil && nextNode.key <= key {
// Go right
currentNode = nextNode
} else {
if index > 0 {
// Early exit
if currentNode.next[0] != nil && math.Abs(currentNode.next[0].key-key) <= t.eps {
foundElem = currentNode.next[0]
ok = true
return
}
// Go down
index--
} else {
// Element is not found and we reached the bottom.
if findGreaterOrEqual {
foundElem = nextNode
ok = nextNode != nil
}
return
}
}
}
}
// Find tries to find an element in the skiplist based on the key from the given ListElement.
// elem can be used, if ok is true.
// Find runs in approx. O(log(n))
func (t *SkipList) Find(e ListElement) (elem *SkipListElement, ok bool) {
if t == nil || e == nil {
return
}
elem, ok = t.findExtended(e.ExtractKey(), false)
return
}
// FindGreaterOrEqual finds the first element, that is greater or equal to the given ListElement e.
// The comparison is done on the keys (So on ExtractKey()).
// FindGreaterOrEqual runs in approx. O(log(n))
func (t *SkipList) FindGreaterOrEqual(e ListElement) (elem *SkipListElement, ok bool) {
if t == nil || e == nil {
return
}
elem, ok = t.findExtended(e.ExtractKey(), true)
return
}
// Delete removes an element equal to e from the skiplist, if there is one.
// If there are multiple entries with the same value, Delete will remove one of them
// (Which one will change based on the actual skiplist layout)
// Delete runs in approx. O(log(n))
func (t *SkipList) DeleteResponse(e ListElement) (*SkipListElement, bool) {
if t == nil || t.IsEmpty() || e == nil {
return nil, false
}
key := e.ExtractKey()
index := t.findEntryIndex(key, 0)
var currentNode *SkipListElement
nextNode := currentNode
for {
if currentNode == nil {
nextNode = t.startLevels[index]
} else {
nextNode = currentNode.next[index]
}
// Found and remove!
if nextNode != nil && math.Abs(nextNode.key-key) <= t.eps {
if currentNode != nil {
currentNode.next[index] = nextNode.next[index]
}
if index == 0 {
if nextNode.next[index] != nil {
nextNode.next[index].prev = currentNode
}
t.elementCount--
}
// Link from start needs readjustments.
if t.startLevels[index] == nextNode {
t.startLevels[index] = nextNode.next[index]
// This was our currently highest node!
if t.startLevels[index] == nil {
t.maxLevel = index - 1
}
}
// Link from end needs readjustments.
if nextNode.next[index] == nil {
t.endLevels[index] = currentNode
}
nextNode.next[index] = nil
}
if nextNode != nil && nextNode.key < key {
// Go right
currentNode = nextNode
} else {
// Go down
index--
if index < 0 {
break
}
}
}
if nextNode != nil {
return nextNode, true
}
return nil, false
}
// Delete removes an element equal to e from the skiplist, if there is one.
// If there are multiple entries with the same value, Delete will remove one of them
// (Which one will change based on the actual skiplist layout)
// Delete runs in approx. O(log(n))
func (t *SkipList) Delete(e ListElement) {
if t == nil || t.IsEmpty() || e == nil {
return
}
key := e.ExtractKey()
index := t.findEntryIndex(key, 0)
var currentNode *SkipListElement
nextNode := currentNode
for {
if currentNode == nil {
nextNode = t.startLevels[index]
} else {
nextNode = currentNode.next[index]
}
// Found and remove!
if nextNode != nil && math.Abs(nextNode.key-key) <= t.eps {
if currentNode != nil {
currentNode.next[index] = nextNode.next[index]
}
if index == 0 {
if nextNode.next[index] != nil {
nextNode.next[index].prev = currentNode
}
t.elementCount--
}
// Link from start needs readjustments.
if t.startLevels[index] == nextNode {
t.startLevels[index] = nextNode.next[index]
// This was our currently highest node!
if t.startLevels[index] == nil {
t.maxLevel = index - 1
}
}
// Link from end needs readjustments.
if nextNode.next[index] == nil {
t.endLevels[index] = currentNode
}
nextNode.next[index] = nil
}
if nextNode != nil && nextNode.key < key {
// Go right
currentNode = nextNode
} else {
// Go down
index--
if index < 0 {
break
}
}
}
}
// Insert inserts the given ListElement into the skiplist.
// Insert runs in approx. O(log(n))
func (t *SkipList) Insert(e ListElement) {
if t == nil || e == nil {
return
}
level := t.generateLevel(t.maxNewLevel)
// Only grow the height of the skiplist by one at a time!
if level > t.maxLevel {
level = t.maxLevel + 1
t.maxLevel = level
}
elem := &SkipListElement{
next: [maxLevel]*SkipListElement{},
level: level,
key: e.ExtractKey(),
value: e,
}
t.elementCount++
newFirst := true
newLast := true
if !t.IsEmpty() {
newFirst = elem.key < t.startLevels[0].key
newLast = elem.key > t.endLevels[0].key
}
normallyInserted := false
if !newFirst && !newLast {
normallyInserted = true
index := t.findEntryIndex(elem.key, level)
var currentNode *SkipListElement
nextNode := t.startLevels[index]
for {
if currentNode == nil {
nextNode = t.startLevels[index]
} else {
nextNode = currentNode.next[index]
}
// Connect node to next
if index <= level && (nextNode == nil || nextNode.key > elem.key) {
elem.next[index] = nextNode
if currentNode != nil {
currentNode.next[index] = elem
}
if index == 0 {
elem.prev = currentNode
if nextNode != nil {
nextNode.prev = elem
}
}
}
if nextNode != nil && nextNode.key <= elem.key {
// Go right
currentNode = nextNode
} else {
// Go down
index--
if index < 0 {
break
}
}
}
}
// Where we have a left-most position that needs to be referenced!
for i := level; i >= 0; i-- {
didSomething := false
if newFirst || normallyInserted {
if t.startLevels[i] == nil || t.startLevels[i].key > elem.key {
if i == 0 && t.startLevels[i] != nil {
t.startLevels[i].prev = elem
}
elem.next[i] = t.startLevels[i]
t.startLevels[i] = elem
}
// link the endLevels to this element!
if elem.next[i] == nil {
t.endLevels[i] = elem
}
didSomething = true
}
if newLast {
// Places the element after the very last element on this level!
// This is very important, so we are not linking the very first element (newFirst AND newLast) to itself!
if !newFirst {
if t.endLevels[i] != nil {
t.endLevels[i].next[i] = elem
}
if i == 0 {
elem.prev = t.endLevels[i]
}
t.endLevels[i] = elem
}
// Link the startLevels to this element!
if t.startLevels[i] == nil || t.startLevels[i].key > elem.key {
t.startLevels[i] = elem
}
didSomething = true
}
if !didSomething {
break
}
}
}
// GetValue extracts the ListElement value from a skiplist node.
func (e *SkipListElement) GetValue() ListElement {
return e.value
}
// GetSmallestNode returns the very first/smallest node in the skiplist.
// GetSmallestNode runs in O(1)
func (t *SkipList) GetSmallestNode() *SkipListElement {
return t.startLevels[0]
}
// GetLargestNode returns the very last/largest node in the skiplist.
// GetLargestNode runs in O(1)
func (t *SkipList) GetLargestNode() *SkipListElement {
return t.endLevels[0]
}
// Next returns the next element based on the given node.
// Next will loop around to the first node, if you call it on the last!
func (t *SkipList) Next(e *SkipListElement) *SkipListElement {
if e.next[0] == nil {
return t.startLevels[0]
}
return e.next[0]
}
// Prev returns the previous element based on the given node.
// Prev will loop around to the last node, if you call it on the first!
func (t *SkipList) Prev(e *SkipListElement) *SkipListElement {
if e.prev == nil {
return t.endLevels[0]
}
return e.prev
}
// GetNodeCount returns the number of nodes currently in the skiplist.
func (t *SkipList) GetNodeCount() int {
return t.elementCount
}
// ChangeValue can be used to change the actual value of a node in the skiplist
// without the need of Deleting and reinserting the node again.
// Be advised, that ChangeValue only works, if the actual key from ExtractKey() will stay the same!
// ok is an indicator, wether the value is actually changed.
func (t *SkipList) ChangeValue(e *SkipListElement, newValue ListElement) (ok bool) {
// The key needs to stay correct, so this is very important!
if math.Abs(newValue.ExtractKey() - e.key) <= t.eps {
e.value = newValue
ok = true
} else {
ok = false
}
return
}
// String returns a string format of the skiplist. Useful to get a graphical overview and/or debugging.
func (t *SkipList) String() string {
s := ""
s += " --> "
for i, l := range t.startLevels {
if l == nil {
break
}
if i > 0 {
s += " -> "
}
next := "---"
if l != nil {
next = l.value.String()
}
s += fmt.Sprintf("[%v]", next)
if i == 0 {
s += " "
}
}
s += "\n"
node := t.startLevels[0]
for node != nil {
s += fmt.Sprintf("%v: ", node.value)
for i := 0; i <= node.level; i++ {
l := node.next[i]
next := "---"
if l != nil {
next = l.value.String()
}
if i == 0 {
prev := "---"
if node.prev != nil {
prev = node.prev.value.String()
}
s += fmt.Sprintf("[%v|%v]", prev, next)
} else {
s += fmt.Sprintf("[%v]", next)
}
if i < node.level {
s += " -> "
}
}
s += "\n"
node = node.next[0]
}
s += " --> "
for i, l := range t.endLevels {
if l == nil {
break
}
if i > 0 {
s += " -> "
}
next := "---"
if l != nil {
next = l.value.String()
}
s += fmt.Sprintf("[%v]", next)
if i == 0 {
s += " "
}
}
s += "\n"
return s
}