diff options
author | Michael Stapelberg <stapelberg@debian.org> | 2013-03-04 21:27:36 +0100 |
---|---|---|
committer | Michael Stapelberg <michael@stapelberg.de> | 2013-03-04 21:27:36 +0100 |
commit | 04b08da9af0c450d645ab7389d1467308cfc2db8 (patch) | |
tree | db247935fa4f2f94408edc3acd5d0d4f997aa0d8 /src/pkg/container/heap/example_intheap_test.go | |
parent | 917c5fb8ec48e22459d77e3849e6d388f93d3260 (diff) | |
download | golang-upstream/1.1_hg20130304.tar.gz |
Imported Upstream version 1.1~hg20130304upstream/1.1_hg20130304
Diffstat (limited to 'src/pkg/container/heap/example_intheap_test.go')
-rw-r--r-- | src/pkg/container/heap/example_intheap_test.go | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/src/pkg/container/heap/example_intheap_test.go b/src/pkg/container/heap/example_intheap_test.go new file mode 100644 index 000000000..e718cbc58 --- /dev/null +++ b/src/pkg/container/heap/example_intheap_test.go @@ -0,0 +1,43 @@ +// 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 and removes them in order of priority. +func Example_intHeap() { + h := &IntHeap{2, 1, 5} + heap.Init(h) + heap.Push(h, 3) + for h.Len() > 0 { + fmt.Printf("%d ", heap.Pop(h)) + } + // Output: 1 2 3 5 +} |