Skip to main content

Priority Queue

SpaceTime
AccessLookupInsertionDeletion
O(n)O(n)O(n)O(1)O(1)

Definition​

Priority Queue is a data structure that allows elements to be inserted and removed based on their priority.

Simplified

You're planning your day with a list of tasks: grocery shopping, work meeting, gym, cooking dinner, and reading a book. However, not all tasks are equally important. Some tasks are urgent and need to be done first, while others can wait.

In this scenario, a "Priority Queue" is like a smart to-do list. It helps you manage your tasks based on their importance or urgency. The task with the highest priority (like a work meeting) gets to be at the front of the queue, meaning it should be done first. Once that task is completed, it's removed from the queue, and the next highest priority task (like grocery shopping) moves to the front.

Practice​

AspectPseudo Code
Heapify Up
heapify_up(index):
if index == 0:
return
parent_index = (index - 1) / 2
if heap[parent_index].value < heap[index].value:
swap(heap, parent_index, index)
heapify_up(parent_index)
Heapify Down
heapify_down():
index = 0
while index < heap.size:
left_child_index=2 * index + 1
right_child_index = 2 * index + 2
smallest_index = -1
if heap.size > left_child_index and heap[left_child_index].value < heap[index].value:
smallest_index = left_child_index
else if heap.size > right_child_index and heap[right_child_index].value < heap[index].value:
smallest_index = right_child_index
else:
break
swap(heap, index, smallest_index)
index = smallest_index

method swap(list, i, j):
temp = list[i]
list[i] = list[j]
list[j] = temp
Enqueue
enqueue(item, priority):
heap.add(Pair(item, priority))
heapify_up(heap.last_index)
Dequeue
dequeue():
if heap == ø:
return ø
highest_priority_item = heap[0].key
heap[0] = heap.last()
heap.remove_at(heap.last_index)
heapify_down()
return highest_priority_item
Peek
peek():
if heap == ø:
return ø
else:
return heap[0].key
Change Priority
change_priority(item, new_priority):
index = heap.find_index(item)
if index != -1:
heap[index] = Pair(item, new_priority)
heapify_up(index)
Find by Value
find_by_value(item: T): T?:
index = heap.find_index(item)
if index != -1:
return heap[index].key
else:
return ø