summaryrefslogtreecommitdiff
path: root/pkg/priority_queue/binary_heap_test.go
blob: 1b510be3f99bc473c04361e9135e2553dbda24d6 (plain)
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
package priorityqueue

import (
	"sort"
	"testing"

	"github.com/stretchr/testify/require"
)

type Test int

func (t Test) ID() string {
	return ""
}

func (t Test) Priority() uint64 {
	return uint64(t)
}

func TestBinHeap_Init(t *testing.T) {
	a := []PQItem{Test(2), Test(23), Test(33), Test(44), Test(1), Test(2), Test(2), Test(2), Test(4), Test(6), Test(99)}

	bh := NewBinHeap()

	bh.Init(a)

	expected := []PQItem{Test(1), Test(2), Test(2), Test(2), Test(2), Test(4), Test(6), Test(23), Test(33), Test(44), Test(99)}

	require.Equal(t, expected, a)
}

func TestBinHeap_Init2(t *testing.T) {
	a := []PQItem{Test(2), Test(23), Test(33), Test(44), Test(1), Test(2), Test(2), Test(2), Test(4), Test(6), Test(99)}

	bh := NewBinHeap()

	for i := 0; i < len(a); i++ {
		bh.Insert(a[i])
	}

	expected := []PQItem{Test(1), Test(2), Test(2), Test(2), Test(2), Test(4), Test(6), Test(23), Test(33), Test(44), Test(99)}

	res := make([]PQItem, 0, 12)

	for i := 0; i < 11; i++ {
		item := bh.GetMax()
		res = append(res, item)
	}

	require.Equal(t, expected, res)
}

func BenchmarkBinHeap_Init(b *testing.B) {
	a := []PQItem{Test(2), Test(23), Test(33), Test(44), Test(1), Test(2), Test(2), Test(2), Test(4), Test(6), Test(99)}
	bh := NewBinHeap()

	b.ResetTimer()
	b.ReportAllocs()

	for i := 0; i < b.N; i++ {
		bh.Init(a)
	}
}

func BenchmarkBinHeap_InitStdSort(b *testing.B) {
	a := []PQItem{Test(2), Test(23), Test(33), Test(44), Test(1), Test(2), Test(2), Test(2), Test(4), Test(6), Test(99)}

	b.ResetTimer()
	b.ReportAllocs()

	for i := 0; i < b.N; i++ {
		sort.Slice(a, func(i, j int) bool {
			return a[i].Priority() < a[j].Priority()
		})
	}
}