Priority Queue
Priority Queue
A priority queue assigns a priority value to each element in the queue. Elements are dequeued based on their priority, with higher-priority elements being processed first. Priority queues are used in scenarios where the order of processing depends on priorities.
Operations
Queue Operations
Enqueue
Adding an element to the back (also known as the rear or tail) of the queue.
Dequeue
Removing and returning the element from the front (also known as the head) of the queue.
Peek
Viewing the element at the front of the queue without removing it.
Demonstration
Priority Queue Interactive Demonstration
Code
Priority Queue Python Code
import heapq class PriorityQueue: def __init__(self): self.elements = [] def is_empty(self): return len(self.elements) == 0 def enqueue(self, item, priority): heapq.heappush(self.elements, (priority, item)) def dequeue(self): if not self.is_empty(): return heapq.heappop(self.elements)[1] else: print("Queue is empty") # Example usage: if __name__ == "__main__": pq = PriorityQueue() pq.enqueue("Task 1", 3) pq.enqueue("Task 2", 1) pq.enqueue("Task 3", 2) print("Dequeue:", pq.dequeue()) # Dequeue Task 2 with the highest priority print("Is empty?", pq.is_empty()) # False print("Dequeue:", pq.dequeue()) # Dequeue Task 3 with the next highest priority print("Dequeue:", pq.dequeue()) # Dequeue Task 1 with the lowest priority print("Is empty?", pq.is_empty()) # True