A priority queue is an abstract data type (ADT) that manages a collection of elements where each element has a priority (often a key). The data structure always returns the element with the best priority next. In a min-priority queue, the smallest key comes out first; in a max-priority queue, the largest does.
Unlike a regular queue (FIFO), the removal order is determined by priority, not insertion time. Priority queues are typically implemented with heaps to achieve good performance guarantees.
Additional considerations include how to compare priorities (custom comparator), how to handle ties (stable vs. unstable), and whether you need to locate and update arbitrary elements (an indexed priority queue).
// Min-heap priority queue (0-based array A)
insert(x):
A.append(x)
sift_up(A.size-1)
peek():
return A[0]
extract_min():
swap A[0], A[last]
min = A.pop()
if A not empty: sift_down(0)
return min
sift_up(i):
while i > 0 and A[i] < A[parent(i)]:
swap A[i], A[parent(i)]
i = parent(i)
sift_down(i):
while has_child(i):
j = index of smaller child of i
if A[i] <= A[j]: break
swap A[i], A[j]
i = j