summaryrefslogtreecommitdiff
path: root/src/pkg/container/heap/heap_test.go
blob: 2375906b967fc1022b8ccfd9c1dd91a928498dd6 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package heap

import (
	"testing";
	"container/vector";
)


type myHeap struct {
	vector.IntVector;
}


func newHeap() *myHeap {
	var h myHeap;
	h.IntVector.Init(0);
	return &h;
}


func (h *myHeap) verify(t *testing.T, i int) {
	n := h.Len();
	j1 := 2*i + 1;
	j2 := 2*i + 2;
	if j1 < n {
		if h.Less(j1, i) {
			t.Errorf("heap invariant invalidated [%d] = %d > [%d] = %d", i, h.At(i), j1, h.At(j1));
			return;
		}
		h.verify(t, j1);
	}
	if j2 < n {
		if h.Less(j2, i) {
			t.Errorf("heap invariant invalidated [%d] = %d > [%d] = %d", i, h.At(i), j1, h.At(j2));
			return;
		}
		h.verify(t, j2);
	}
}


func (h *myHeap) Push(x interface{})	{ h.IntVector.Push(x.(int)) }


func (h *myHeap) Pop() interface{}	{ return h.IntVector.Pop() }


func TestInit(t *testing.T) {
	h := newHeap();
	for i := 20; i > 0; i-- {
		h.Push(i);
	}
	Init(h);
	h.verify(t, 0);

	for i := 1; h.Len() > 0; i++ {
		x := Pop(h).(int);
		h.verify(t, 0);
		if x != i {
			t.Errorf("%d.th pop got %d; want %d", i, x, i);
		}
	}
}


func Test(t *testing.T) {
	h := newHeap();
	h.verify(t, 0);

	for i := 20; i > 10; i-- {
		h.Push(i);
	}
	Init(h);
	h.verify(t, 0);

	for i := 10; i > 0; i-- {
		Push(h, i);
		h.verify(t, 0);
	}

	for i := 1; h.Len() > 0; i++ {
		x := Pop(h).(int);
		if i < 20 {
			Push(h, 20+i);
		}
		h.verify(t, 0);
		if x != i {
			t.Errorf("%d.th pop got %d; want %d", i, x, i);
		}
	}
}