Class: DSA::PriorityQueue
- Inherits:
-
Object
- Object
- DSA::PriorityQueue
- Defined in:
- lib/dsa-ruby/priority_queue.rb
Overview
DSA::PriorityQueue - A priority queue data structure.
Uses a heap internally to provide efficient priority-based ordering. Supports both min and max priority ordering.
Instance Method Summary collapse
-
#empty? ⇒ Boolean
Checks if the priority queue is empty.
-
#initialize(type: :min) ⇒ DSA::PriorityQueue
constructor
Initialize a new priority queue.
-
#peek ⇒ Object
Returns the item with the highest/lowest priority without removing it.
-
#pop ⇒ Object
Removes and returns the item with the highest/lowest priority.
-
#priority_peek ⇒ Comparable
Returns the priority value of the top item without removing it.
-
#push(item, priority) ⇒ DSA::PriorityQueue
Inserts an item with a given priority.
-
#size ⇒ Integer
Returns the number of items in the priority queue.
Constructor Details
#initialize(type: :min) ⇒ DSA::PriorityQueue
Initialize a new priority queue.
26 27 28 |
# File 'lib/dsa-ruby/priority_queue.rb', line 26 def initialize(type: :min) @heap = type == :min ? MinHeap.new : MaxHeap.new end |
Instance Method Details
#empty? ⇒ Boolean
Checks if the priority queue is empty.
100 101 102 |
# File 'lib/dsa-ruby/priority_queue.rb', line 100 def empty? @heap.empty? end |
#peek ⇒ Object
Returns the item with the highest/lowest priority without removing it.
66 67 68 69 70 |
# File 'lib/dsa-ruby/priority_queue.rb', line 66 def peek raise IndexError, "priority queue is empty" if empty? _, _, item = @heap.peek item end |
#pop ⇒ Object
Removes and returns the item with the highest/lowest priority.
52 53 54 55 56 |
# File 'lib/dsa-ruby/priority_queue.rb', line 52 def pop raise IndexError, "priority queue is empty" if empty? _, _, item = @heap.pop item end |
#priority_peek ⇒ Comparable
Returns the priority value of the top item without removing it.
79 80 81 82 |
# File 'lib/dsa-ruby/priority_queue.rb', line 79 def priority_peek raise IndexError, "priority queue is empty" if empty? @heap.peek[0] end |
#push(item, priority) ⇒ DSA::PriorityQueue
Inserts an item with a given priority.
37 38 39 40 41 42 |
# File 'lib/dsa-ruby/priority_queue.rb', line 37 def push(item, priority) @counter ||= 0 @heap.push([priority, @counter, item]) @counter += 1 self end |
#size ⇒ Integer
Returns the number of items in the priority queue.
90 91 92 |
# File 'lib/dsa-ruby/priority_queue.rb', line 90 def size @heap.size end |