Lecture 6 Heaps and Priority Queues
Lecture 6 Heaps and Priority Queues
PRIORITY
Some applications of queues require items
processed in order of "key" or priority
rather than in order of entry (FIFO)
Priority Queues (PQueues or PQs) provide this via:
PRIORITY QUEUES
insert item
delete item with highest priority key
COMPARISON OF POSSIBLE
IMPLEMENTATIONS
Implementation
ordered array/list
unordered array/list
insert delete
O(N)
O(1)
O(1)
O(N)
operations efficiently?
HEAPS
Heap-ordered trees
HEAP IMPLEMENTATIONS
BSTs are typically implemented as linked data
structures
Heaps CAN be implemented as linked data
structures
HEAP INSERTION
Bottom-up heapify:
// force value at a[k] into correct position
void fixUp(Item a[], int k) {
while (k > 1 && less(a[k/2],a[k])) {
swap(a, k, k/2);
k = k/2; // integer division
}
}
HEAP INSERTION
Top-down heapify:
EXERCISE:
HEAPSFUN