File: tinyqueue.go

package info (click to toggle)
golang-github-tidwall-tinyqueue 0.0~git20180302.1e39f55-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 60 kB
  • sloc: makefile: 2
file content (86 lines) | stat: -rw-r--r-- 1,332 bytes parent folder | download
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
package tinyqueue

type Queue struct {
	length int
	data   []Item
}

type Item interface {
	Less(Item) bool
}

func New(data []Item) *Queue {
	q := &Queue{}
	q.data = data
	q.length = len(data)
	if q.length > 0 {
		i := q.length >> 1
		for ; i >= 0; i-- {
			q.down(i)
		}
	}
	return q
}

func (q *Queue) Push(item Item) {
	q.data = append(q.data, item)
	q.length++
	q.up(q.length - 1)
}
func (q *Queue) Pop() Item {
	if q.length == 0 {
		return nil
	}
	top := q.data[0]
	q.length--
	if q.length > 0 {
		q.data[0] = q.data[q.length]
		q.down(0)
	}
	q.data = q.data[:len(q.data)-1]
	return top
}
func (q *Queue) Peek() Item {
	if q.length == 0 {
		return nil
	}
	return q.data[0]
}
func (q *Queue) Len() int {
	return q.length
}
func (q *Queue) down(pos int) {
	data := q.data
	halfLength := q.length >> 1
	item := data[pos]
	for pos < halfLength {
		left := (pos << 1) + 1
		right := left + 1
		best := data[left]
		if right < q.length && data[right].Less(best) {
			left = right
			best = data[right]
		}
		if !best.Less(item) {
			break
		}
		data[pos] = best
		pos = left
	}
	data[pos] = item
}

func (q *Queue) up(pos int) {
	data := q.data
	item := data[pos]
	for pos > 0 {
		parent := (pos - 1) >> 1
		current := data[parent]
		if !item.Less(current) {
			break
		}
		data[pos] = current
		pos = parent
	}
	data[pos] = item
}