Class: DSA::MinHeap
- Inherits:
-
Object
- Object
- DSA::MinHeap
- Defined in:
- lib/dsa-ruby/heap.rb
Overview
DSA::MinHeap - A min-heap (priority queue) data structure.
The smallest element is always at the root. Provides O(log n) insertion and extraction of the minimum element.
Instance Method Summary collapse
-
#empty? ⇒ Boolean
Checks if the heap is empty.
-
#initialize(elements = []) ⇒ DSA::MinHeap
constructor
Initialize a new min-heap with optional initial elements.
-
#peek ⇒ Comparable
Returns the minimum element without removing it.
-
#pop ⇒ Comparable
Removes and returns the minimum element from the heap.
-
#push(val) ⇒ DSA::MinHeap
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::MinHeap
Initialize a new min-heap with optional initial elements.
21 22 23 24 |
# File 'lib/dsa-ruby/heap.rb', line 21 def initialize(elements = []) @elements = [] elements.each { |e| push(e) } end |
Instance Method Details
#empty? ⇒ Boolean
Checks if the heap is empty.
82 83 84 |
# File 'lib/dsa-ruby/heap.rb', line 82 def empty? @elements.empty? end |
#peek ⇒ Comparable
Returns the minimum element without removing it.
61 62 63 64 |
# File 'lib/dsa-ruby/heap.rb', line 61 def peek raise IndexError, "heap is empty" if empty? @elements[0] end |
#pop ⇒ Comparable
Removes and returns the minimum element from the heap.
45 46 47 48 49 50 51 52 |
# File 'lib/dsa-ruby/heap.rb', line 45 def pop raise IndexError, "heap is empty" if empty? swap(0, @elements.size - 1) min = @elements.pop sift_down(0) min end |
#push(val) ⇒ DSA::MinHeap
Inserts an element into the heap.
32 33 34 35 36 |
# File 'lib/dsa-ruby/heap.rb', line 32 def push(val) @elements << val sift_up(@elements.size - 1) self end |
#size ⇒ Integer
Returns the number of elements in the heap.
72 73 74 |
# File 'lib/dsa-ruby/heap.rb', line 72 def size @elements.size end |
#to_a ⇒ Array<Comparable>
Returns a defensive copy of the heap as an array.
92 93 94 |
# File 'lib/dsa-ruby/heap.rb', line 92 def to_a @elements.dup end |