github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/container/heap/heap.go (about) 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. 4 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. 8 // 9 // The minimum element in the tree is the root, at index 0. 10 // 11 // A heap is a common way to implement a priority queue. To build a priority 12 // queue, implement the Heap interface with the (negative) priority as the 13 // ordering for the Less method, so Push adds items while Pop removes the 14 // highest-priority item from the queue. The Examples include such an 15 // implementation; the file example_pq_test.go has the complete source. 16 package heap 17 18 import "github.com/shogo82148/std/sort" 19 20 // The Interface type describes the requirements 21 // for a type using the routines in this package. 22 // Any type that implements it may be used as a 23 // min-heap with the following invariants (established after 24 // [Init] has been called or if the data is empty or sorted): 25 // 26 // !h.Less(j, i) for 0 <= i < h.Len() and 2*i+1 <= j <= 2*i+2 and j < h.Len() 27 // 28 // Note that [Push] and [Pop] in this interface are for package heap's 29 // implementation to call. To add and remove things from the heap, 30 // use [heap.Push] and [heap.Pop]. 31 type Interface interface { 32 sort.Interface 33 Push(x any) 34 Pop() any 35 } 36 37 // Init establishes the heap invariants required by the other routines in this package. 38 // Init is idempotent with respect to the heap invariants 39 // and may be called whenever the heap invariants may have been invalidated. 40 // The complexity is O(n) where n = h.Len(). 41 func Init(h Interface) 42 43 // Push pushes the element x onto the heap. 44 // The complexity is O(log n) where n = h.Len(). 45 func Push(h Interface, x any) 46 47 // Pop removes and returns the minimum element (according to Less) from the heap. 48 // The complexity is O(log n) where n = h.Len(). 49 // Pop is equivalent to [Remove](h, 0). 50 func Pop(h Interface) any 51 52 // Remove removes and returns the element at index i from the heap. 53 // The complexity is O(log n) where n = h.Len(). 54 func Remove(h Interface, i int) any 55 56 // Fix re-establishes the heap ordering after the element at index i has changed its value. 57 // Changing the value of the element at index i and then calling Fix is equivalent to, 58 // but less expensive than, calling [Remove](h, i) followed by a Push of the new value. 59 // The complexity is O(log n) where n = h.Len(). 60 func Fix(h Interface, i int)