Professional Documents
Culture Documents
Heaps
Heap: Complete binary tree with the heap property:
Min-heap: All values less than child values. Max-heap: All values greater than child values.
Heap example
Parent of v[k] = v[(k-1)/2] Left child of v[k] = v[2*k+1] Right child of v[k] = v[2*k + 2]
A B D I J E F C G
A 0
B 1
C 2
D 3
E 4
F 5
G H 6 7
Dr. Khalil Challita
I 8
J 9
10 11 12 13
3
(a) (4-2) (4-1) (2-1) (5-2) (5-4) (6-3) (6-5) (7-5) (7-6) (b) Steps of BuildHeap: (5-2), (7-3), (7-1), (6-1)
Dr. Khalil Challita 4
Priority Queues
When a collection of objects is organized by importance or priority, we call this a priority queue.
Example: Scheduling jobs in a multi-tasking operating system. The priority of a job may change, requiring some reordering of the jobs.
Implementation: Use a heap to store the priority queue, since a normal queue data structure will not implement a priority queue efficiently.
// Number of elements in heap const Comparable HEAP_EMPTY; vector<Comparable> array; // The heap array void buildHeap( ); void percolateDown( int hole );
};