Class: DSA::MaxHeap
- Inherits:
-
Object
- Object
- DSA::MaxHeap
- Defined in:
- lib/dsa-ruby/heap.rb
Overview
DSA::MaxHeap - A max-heap (priority queue) data structure.
The largest element is always at the root. Provides O(log n) insertion and extraction of the maximum element.
Instance Method Summary collapse
-
#empty? ⇒ Boolean
Checks if the heap is empty.
-
#initialize(elements = []) ⇒ DSA::MaxHeap
constructor
Initialize a new max-heap with optional initial elements.
-
#peek ⇒ Comparable
Returns the maximum element without removing it.
-
#pop ⇒ Comparable
Removes and returns the maximum element from the heap.
-
#push(val) ⇒ DSA::MaxHeap
Inserts an element into the heap.
-
#size ⇒ Integer
Returns the number of elements in the heap.
-
#to_a ⇒ Array<Comparable>
Returns a defensive copy of the heap as an array.
Constructor Details
#initialize(elements = []) ⇒ DSA::MaxHeap
Initialize a new max-heap with optional initial elements.
156 157 158 159 |
# File 'lib/dsa-ruby/heap.rb', line 156 def initialize(elements = []) @elements = [] elements.each { |e| push(e) } end |
Instance Method Details
#empty? ⇒ Boolean
Checks if the heap is empty.
217 218 219 |
# File 'lib/dsa-ruby/heap.rb', line 217 def empty? @elements.empty? end |
#peek ⇒ Comparable
Returns the maximum element without removing it.
196 197 198 199 |
# File 'lib/dsa-ruby/heap.rb', line 196 def peek raise IndexError, "heap is empty" if empty? @elements[0] end |
#pop ⇒ Comparable
Removes and returns the maximum element from the heap.
180 181 182 183 184 185 186 187 |
# File 'lib/dsa-ruby/heap.rb', line 180 def pop raise IndexError, "heap is empty" if empty? swap(0, @elements.size - 1) max = @elements.pop sift_down(0) max end |
#push(val) ⇒ DSA::MaxHeap
Inserts an element into the heap.
167 168 169 170 171 |
# File 'lib/dsa-ruby/heap.rb', line 167 def push(val) @elements << val sift_up(@elements.size - 1) self end |
#size ⇒ Integer
Returns the number of elements in the heap.
207 208 209 |
# File 'lib/dsa-ruby/heap.rb', line 207 def size @elements.size end |
#to_a ⇒ Array<Comparable>
Returns a defensive copy of the heap as an array.
227 228 229 |
# File 'lib/dsa-ruby/heap.rb', line 227 def to_a @elements.dup end |