Debian Codegraph @

trees/binaryheap/binaryheap.go

raw symbols SCIP
1 // Copyright (c) 2015, Emir Pasic. 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 binaryheap implements a binary heap backed by array list.
6 //
7 // Comparator defines this heap as either min or max heap.
8 //
9 // Structure is not thread safe.
10 //
11 // References: http://en.wikipedia.org/wiki/Binary_heap
12 package binaryheap
13
14 import (
15 "cmp"
16 "fmt"
17 "strings"
18
19 "github.com/emirpasic/gods/v2/lists/arraylist"
20 "github.com/emirpasic/gods/v2/trees"
21 "github.com/emirpasic/gods/v2/utils"
22 )
23
24 // Assert Tree implementation
25 var _ trees.Tree[int] = (*Heap[int])(nil)
26
27 // Heap holds elements in an array-list
28 type Heap[T comparable] struct {
29 list *arraylist.List[T]
30 Comparator utils.Comparator[T]
31 }
32
33 // New instantiates a new empty heap tree with the built-in comparator for T
34 func New[T cmp.Ordered]() *Heap[T] {
35 return &Heap[T]{list: arraylist.New[T](), Comparator: cmp.Compare[T]}
36 }
37
38 // NewWith instantiates a new empty heap tree with the custom comparator.
39 func NewWith[T comparable](comparator utils.Comparator[T]) *Heap[T] {
40 return &Heap[T]{list: arraylist.New[T](), Comparator: comparator}
41 }
42
43 // Push adds a value onto the heap and bubbles it up accordingly.
44 func (heap *Heap[T]) Push(values ...T) {
45 if len(values) == 1 {
46 heap.list.Add(values[0])
47 heap.bubbleUp()
48 } else {
49 // Reference: https://en.wikipedia.org/wiki/Binary_heap#Building_a_heap
50 for _, value := range values {
51 heap.list.Add(value)
52 }
53 size := heap.list.Size()/2 + 1
54 for i := size; i >= 0; i-- {
55 heap.bubbleDownIndex(i)
56 }
57 }
58 }
59
60 // Pop removes top element on heap and returns it, or nil if heap is empty.
61 // Second return parameter is true, unless the heap was empty and there was nothing to pop.
62 func (heap *Heap[T]) Pop() (value T, ok bool) {
63 value, ok = heap.list.Get(0)
64 if !ok {
65 return
66 }
67 lastIndex := heap.list.Size() - 1
68 heap.list.Swap(0, lastIndex)
69 heap.list.Remove(lastIndex)
70 heap.bubbleDown()
71 return
72 }
73
74 // Peek returns top element on the heap without removing it, or nil if heap is empty.
75 // Second return parameter is true, unless the heap was empty and there was nothing to peek.
76 func (heap *Heap[T]) Peek() (value T, ok bool) {
77 return heap.list.Get(0)
78 }
79
80 // Empty returns true if heap does not contain any elements.
81 func (heap *Heap[T]) Empty() bool {
82 return heap.list.Empty()
83 }
84
85 // Size returns number of elements within the heap.
86 func (heap *Heap[T]) Size() int {
87 return heap.list.Size()
88 }
89
90 // Clear removes all elements from the heap.
91 func (heap *Heap[T]) Clear() {
92 heap.list.Clear()
93 }
94
95 // Values returns all elements in the heap.
96 func (heap *Heap[T]) Values() []T {
97 values := make([]T, heap.list.Size(), heap.list.Size())
98 for it := heap.Iterator(); it.Next(); {
99 values[it.Index()] = it.Value()
100 }
101 return values
102 }
103
104 // String returns a string representation of container
105 func (heap *Heap[T]) String() string {
106 str := "BinaryHeap\n"
107 values := []string{}
108 for it := heap.Iterator(); it.Next(); {
109 values = append(values, fmt.Sprintf("%v", it.Value()))
110 }
111 str += strings.Join(values, ", ")
112 return str
113 }
114
115 // Performs the "bubble down" operation. This is to place the element that is at the root
116 // of the heap in its correct place so that the heap maintains the min/max-heap order property.
117 func (heap *Heap[T]) bubbleDown() {
118 heap.bubbleDownIndex(0)
119 }
120
121 // Performs the "bubble down" operation. This is to place the element that is at the index
122 // of the heap in its correct place so that the heap maintains the min/max-heap order property.
123 func (heap *Heap[T]) bubbleDownIndex(index int) {
124 size := heap.list.Size()
125 for leftIndex := index<<1 + 1; leftIndex < size; leftIndex = index<<1 + 1 {
126 rightIndex := index<<1 + 2
127 smallerIndex := leftIndex
128 leftValue, _ := heap.list.Get(leftIndex)
129 rightValue, _ := heap.list.Get(rightIndex)
130 if rightIndex < size && heap.Comparator(leftValue, rightValue) > 0 {
131 smallerIndex = rightIndex
132 }
133 indexValue, _ := heap.list.Get(index)
134 smallerValue, _ := heap.list.Get(smallerIndex)
135 if heap.Comparator(indexValue, smallerValue) > 0 {
136 heap.list.Swap(index, smallerIndex)
137 } else {
138 break
139 }
140 index = smallerIndex
141 }
142 }
143
144 // Performs the "bubble up" operation. This is to place a newly inserted
145 // element (i.e. last element in the list) in its correct place so that
146 // the heap maintains the min/max-heap order property.
147 func (heap *Heap[T]) bubbleUp() {
148 index := heap.list.Size() - 1
149 for parentIndex := (index - 1) >> 1; index > 0; parentIndex = (index - 1) >> 1 {
150 indexValue, _ := heap.list.Get(index)
151 parentValue, _ := heap.list.Get(parentIndex)
152 if heap.Comparator(parentValue, indexValue) <= 0 {
153 break
154 }
155 heap.list.Swap(index, parentIndex)
156 index = parentIndex
157 }
158 }
159
160 // Check that the index is within bounds of the list
161 func (heap *Heap[T]) withinRange(index int) bool {
162 return index >= 0 && index < heap.list.Size()
163 }