forked from bjarneh/binheap
/
binheap_test.go
132 lines (93 loc) · 2.39 KB
/
binheap_test.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
// Copyright 2011 bjarneh@ifi.uio.no. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package binheap_test
import (
"rand"
"sort"
"testing"
. "github.com/bjarneh/binheap"
)
type heaper struct {
i int
}
func (h *heaper) Priority() int {
return h.i
}
func randomInts(size int) (slice []int) {
slice = make([]int, size)
for i := 0; i < size; i++ {
slice[i] = rand.Int()
}
return slice
}
func randomHeapable(size int) (slice []Heapable) {
ints := randomInts(size)
slice = make([]Heapable, size)
for i := 0; i < size; i++ {
slice[i] = &heaper{ints[i]}
}
return slice
}
func TestIntSort(t *testing.T) {
nums := randomInts(1000)
SortInt(nums)
for i := 1; i < len(nums); i++ {
if nums[i-1] > nums[i] {
t.Fatalf("binheap.SortInts() does not sort\n")
}
}
}
func TestSort(t *testing.T) {
nums := randomHeapable(1000)
Sort(nums)
for i := 1; i < len(nums); i++ {
if nums[i-1].Priority() > nums[i].Priority() {
t.Fatalf("binheap.Sort() does not sort\n")
}
}
}
func TestHeap(t *testing.T) {
heap := NewSize(1) // make it short to test resize
nums := randomInts(1000)
elmts := make([]Heapable, len(nums))
for i := 0; i < len(nums); i++ {
elmts[i] = &heaper{nums[i]}
}
heap.AddSlice(elmts)
if heap.Len() != len(nums) {
t.Fatalf("heap.Len() != %d\n", len(nums))
}
sort.SortInts(nums)
for i := 0; i < len(nums); i++ {
if heap.Remove().Priority() != nums[i] {
t.Fatalf("binheap: Priority() != %d\n", nums[i])
}
}
if !heap.Empty() {
t.Fatalf("heap not empty\n")
}
nums = randomInts(1000)
// add single elements.. i.e. not slice
for i := 0; i < len(nums); i++ {
heap.Add(&heaper{nums[i]})
}
sort.SortInts(nums)
for i := 0; i < len(nums); i++ {
if heap.Remove().Priority() != nums[i] {
t.Fatalf("binheap: Priority() != %d\n", nums[i])
}
}
}
func BenchmarkStdlibSortInts(b *testing.B) {
for i := 0; i < b.N; i++ {
nums := randomInts(1000)
sort.SortInts(nums)
}
}
func BenchmarkHeapSortInt(b *testing.B) {
for i := 0; i < b.N; i++ {
nums := randomInts(1000)
SortInt(nums)
}
}