LEFT | RIGHT |
(no file at all) | |
1 // Copyright 2009 The Go Authors. All rights reserved. | 1 // Copyright 2009 The Go Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style | 2 // Use of this source code is governed by a BSD-style |
3 // license that can be found in the LICENSE file. | 3 // license that can be found in the LICENSE file. |
4 | 4 |
5 // Package heap provides heap operations for any type that implements | 5 // Package heap provides heap operations for any type that implements |
6 // heap.Interface. | 6 // heap.Interface. |
7 // | 7 // |
8 package heap | 8 package heap |
9 | 9 |
10 import "sort" | 10 import "sort" |
11 | 11 |
12 // Any type that implements heap.Interface may be used as a | 12 // Any type that implements heap.Interface may be used as a |
13 // min-heap with the following invariants (established after | 13 // min-heap with the following invariants (established after |
14 // Init has been called): | 14 // Init has been called): |
15 // | 15 // |
16 // !h.Less(j, i) for 0 <= i < h.Len() and j = 2*i+1 or 2*i+2 and j < h.Len(
) | 16 // !h.Less(j, i) for 0 <= i < h.Len() and j = 2*i+1 or 2*i+2 and j < h.Len(
) |
17 // | 17 // |
18 type Interface interface { | 18 type Interface interface { |
19 sort.Interface | 19 sort.Interface |
20 Push(x interface{}) | 20 Push(x interface{}) |
21 Pop() interface{} | 21 Pop() interface{} |
22 } | 22 } |
23 | 23 |
24 | 24 |
25 // A heaper must be initialized before any of the heap operations | 25 // A heap must be initialized before any of the heap operations |
26 // can be used. Init is idempotent with respect to the heap invariants | 26 // can be used. Init is idempotent with respect to the heap invariants |
27 // and may be called whenever the heap invariants may have been invalidated. | 27 // and may be called whenever the heap invariants may have been invalidated. |
28 // Its complexity is O(n) where n = h.Len(). | 28 // Its complexity is O(n) where n = h.Len(). |
29 // | 29 // |
30 func Init(h Interface) { | 30 func Init(h Interface) { |
31 // heapify | 31 // heapify |
32 n := h.Len() | 32 n := h.Len() |
33 for i := n/2 - 1; i >= 0; i-- { | 33 for i := n/2 - 1; i >= 0; i-- { |
34 down(h, i, n) | 34 down(h, i, n) |
35 } | 35 } |
(...skipping 57 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
93 if j2 := j1 + 1; j2 < n && !h.Less(j1, j2) { | 93 if j2 := j1 + 1; j2 < n && !h.Less(j1, j2) { |
94 j = j2 // = 2*i + 2 // right child | 94 j = j2 // = 2*i + 2 // right child |
95 } | 95 } |
96 if h.Less(i, j) { | 96 if h.Less(i, j) { |
97 break | 97 break |
98 } | 98 } |
99 h.Swap(i, j) | 99 h.Swap(i, j) |
100 i = j | 100 i = j |
101 } | 101 } |
102 } | 102 } |
LEFT | RIGHT |