heaps Flashcards
Priority Queue ADT
Priority Queue is an extension of queue with following properties:
* Entries consist of key (priority) and value.
* Entries in priority queue are ordered by key
* An entry with high key is dequeued before an element with low key.
* If two entries have the same key, they are served according to their order in the queue.
Priority Queue operations
A typical priority queue supports following operations:
* insert(key, value): Inserts an item with given key.
* min/max(): Returns the smallest/largest key item.
* removemin/removemax(): Removes the smallest/largest key item.
heap property
if π is a parent node of πΆ, then the key of π is either greater than or equal to (in a max heap) or less than or equal to (in a min heap) the key of πΆ.
max heap
A max heap is a heap such that for each node except the root, the parent of node π is greater than or equal to node π (max-heap property)
Heap as a Tree
root of tree: first element in the array, corresponding to π=1
parent(π)=π/2: returns the index of nodeβs parent
left(π)=2π: returns the index of nodeβs left child
right(π)=2π+1: returns the index of nodeβs right child
all these cost O(1)
max heap operations
max: return the maximum item
extract_max: return and remove the maximum item
build_max_heap: produce a max-heap from an unordered array
max_heapify: correct a single violation of the heap property in a subtree at its root
insert
heapsort
max heapify pseudocode
max_heapify(A, i):
l = left(i)
r = right(i)
if (l <= heap-size(A) and A[l] > A[i])
then largest = l else largest = i
if (r <= heap-size(A) and A[r] > A[largest])
then largest = r
if largest != i
then exchange A[i] and A[largest]
max_heapify(A, largest)
build_max_heap(A)
build_max_heap(A):
for i=n/2 down to 1
do max_heapify(A, i)
Time=O(n) where n is number of elements in the array
Heapsort Sorting Strategy
Build Max Heap from unordered array;
Find maximum element π΄[1];
Swap elements π΄[π] and π΄[1]: now max element is at the end of the array!
Discard node π from heap (by decrementing heap-size variable)
New root may violate max heap property, but its children are max heaps. Run max_heapify to fix this.
Go to Step 2 unless heap is empty.
Heapsort Running time
after π iterations the Heap is empty
every iteration involves a swap and a max_heapify operation;
hence it takes π(π logβ‘π) time overall