Learnearn.uk » IB Computer Science » Priority Queue

# Priority Queue

## 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.

## 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()