What Is A Priority Queue
What Is A Priority Queue
• A priority queue is a special type of queue where each element is associated with a
priority.
• Higher-priority elements are processed first compared to lower-priority elements — even
if lower-priority elements arrived earlier.
• It does not strictly follow FIFO like a simple queue — the order depends on priority first,
and arrival order if priorities are the same.
Example:
Imagine an emergency room:
• A critical patient (high priority) is treated before someone with a small injury (low priority),
even if the small injury patient came first.
Applications:
• Priority queues are used in applications where certain tasks or data elements need
to be processed with higher priority
• Examples include operating system task scheduling and network packet scheduling
OPERATIONS:
• Insertion: Adds an element based on its priority using the heap property. Higher
priority elements are placed closer to the front.
heapq.heappush() puts it in the right spot based on priority.
• Deletion: Removes the element with the highest priority (usually at the root of the
heap).
heapq.heappop() removes the top-priority (lowest number) order.
• Peek: Returns the highest priority element without removing it from the queue.
heapq.heapify() / orders[0]
CODE:
Output:
o Use a while loop to keep serving orders until the list is empty.
o In the loop, use heapq.heappop() to remove and return the pizza with the highest
priority (lowest number).
SUMMARY: