summaryrefslogtreecommitdiffstats
path: root/src/container/heap/example_intheap_test.go
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-28 13:14:23 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-28 13:14:23 +0000
commit73df946d56c74384511a194dd01dbe099584fd1a (patch)
treefd0bcea490dd81327ddfbb31e215439672c9a068 /src/container/heap/example_intheap_test.go
parentInitial commit. (diff)
downloadgolang-1.16-73df946d56c74384511a194dd01dbe099584fd1a.tar.xz
golang-1.16-73df946d56c74384511a194dd01dbe099584fd1a.zip
Adding upstream version 1.16.10.upstream/1.16.10upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/container/heap/example_intheap_test.go')
-rw-r--r--src/container/heap/example_intheap_test.go47
1 files changed, 47 insertions, 0 deletions
diff --git a/src/container/heap/example_intheap_test.go b/src/container/heap/example_intheap_test.go
new file mode 100644
index 0000000..02d3d86
--- /dev/null
+++ b/src/container/heap/example_intheap_test.go
@@ -0,0 +1,47 @@
+// Copyright 2012 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.
+
+// This example demonstrates an integer heap built using the heap interface.
+package heap_test
+
+import (
+ "container/heap"
+ "fmt"
+)
+
+// An IntHeap is a min-heap of ints.
+type IntHeap []int
+
+func (h IntHeap) Len() int { return len(h) }
+func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
+func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
+
+func (h *IntHeap) Push(x interface{}) {
+ // Push and Pop use pointer receivers because they modify the slice's length,
+ // not just its contents.
+ *h = append(*h, x.(int))
+}
+
+func (h *IntHeap) Pop() interface{} {
+ old := *h
+ n := len(old)
+ x := old[n-1]
+ *h = old[0 : n-1]
+ return x
+}
+
+// This example inserts several ints into an IntHeap, checks the minimum,
+// and removes them in order of priority.
+func Example_intHeap() {
+ h := &IntHeap{2, 1, 5}
+ heap.Init(h)
+ heap.Push(h, 3)
+ fmt.Printf("minimum: %d\n", (*h)[0])
+ for h.Len() > 0 {
+ fmt.Printf("%d ", heap.Pop(h))
+ }
+ // Output:
+ // minimum: 1
+ // 1 2 3 5
+}