1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package heap provides heap operations for any type that implements
6 // heap.Interface. A heap is a tree with the property that each node is the
7 // minimum-valued node in its subtree.
9 // A heap is a common way to implement a priority queue. To build a priority
10 // queue, implement the Heap interface with the (negative) priority as the
11 // ordering for the Less method, so Push adds items while Pop removes the
12 // highest-priority item from the queue. The Examples include such an
13 // implementation; the file example_pq_test.go has the complete source.
19 // Any type that implements heap.Interface may be used as a
20 // min-heap with the following invariants (established after
21 // Init has been called or if the data is empty or sorted):
23 // !h.Less(j, i) for 0 <= i < h.Len() and j = 2*i+1 or 2*i+2 and j < h.Len()
25 // Note that Push and Pop in this interface are for package heap's
26 // implementation to call. To add and remove things from the heap,
27 // use heap.Push and heap.Pop.
28 type Interface
interface {
30 Push(x
interface{}) // add x as element Len()
31 Pop() interface{} // remove and return element Len() - 1.
34 // A heap must be initialized before any of the heap operations
35 // can be used. Init is idempotent with respect to the heap invariants
36 // and may be called whenever the heap invariants may have been invalidated.
37 // Its complexity is O(n) where n = h.Len().
39 func Init(h Interface
) {
42 for i
:= n
/2 - 1; i
>= 0; i
-- {
47 // Push pushes the element x onto the heap. The complexity is
48 // O(log(n)) where n = h.Len().
50 func Push(h Interface
, x
interface{}) {
55 // Pop removes the minimum element (according to Less) from the heap
56 // and returns it. The complexity is O(log(n)) where n = h.Len().
57 // Same as Remove(h, 0).
59 func Pop(h Interface
) interface{} {
66 // Remove removes the element at index i from the heap.
67 // The complexity is O(log(n)) where n = h.Len().
69 func Remove(h Interface
, i
int) interface{} {
79 func up(h Interface
, j
int) {
81 i
:= (j
- 1) / 2 // parent
82 if i
== j ||
!h
.Less(j
, i
) {
90 func down(h Interface
, i
, n
int) {
93 if j1
>= n || j1
< 0 { // j1 < 0 after int overflow
97 if j2
:= j1
+ 1; j2
< n
&& !h
.Less(j1
, j2
) {
98 j
= j2
// = 2*i + 2 // right child