A priority queue is a queue where the most important element is always at the front.
The queue can be a max-priority queue (largest element first) or a min-priority queue (smallest element first).
Priority queues are useful for algorithms that need to process a (large) number of items and where you repeatedly need to identify which one is now the biggest or smallest -- or however you define "most important".
Examples of algorithms that can benefit from a priority queue:
With a regular queue or plain old array you'd need to scan the entire sequence over and over to find the next largest item. A priority queue is optimized for this sort of thing.
Common operations on a priority queue:
There are different ways to implement priority queues:
Here's a Swift priority queue based on a heap:
public struct PriorityQueue<T> {
fileprivate var heap: Heap<T>
public init(sort: (T, T) -> Bool) {
heap = Heap(sort: sort)
}
public var isEmpty: Bool {
return heap.isEmpty
}
public var count: Int {
return heap.count
}
public func peek() -> T? {
return heap.peek()
}
public mutating func enqueue(element: T) {
heap.insert(element)
}
public mutating func dequeue() -> T? {
return heap.remove()
}
public mutating func changePriority(index i: Int, value: T) {
return heap.replace(index: i, value: value)
}
}
As you can see, there's nothing much to it. Making a priority queue is easy if you have a heap because a heap is pretty much a priority queue.
Written for Swift Algorithm Club by Matthijs Hollemans