

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


http://www.cs.virginia.edu/~cs216/notes/slides/heaps.pdf
This algorithm inserts the value val into a heap containing n elements. The array v represents the heap.
Input Parameters: val,v,n Output Parameters: v,n
heap_insert(val,v,n) { i = n = n + 1 // i is the child and i/2 is the parent. // If i > 1, i is not the root. while (i > 1 && val > v[i/2]) { v[i] = v[i/2] i = i/ } v[i] = val }
Siftdown: Fix a Heap if Root Wrong
// Input Parameter:v,i,n Output Parameters:v siftdown(v,i,n) { temp = v[i] // 2 * i ⤠n tests for a left child while (2 * i ⤠n) { child = 2 * i // if there is a right child and it is // bigger than the left child, move child if (child < n && v[child + 1] > v[child]) child = child + 1 // move child up? if (v[child] > temp) v[i] = v[child] else break // exit while loop i = child } // insert original v[i] in correct spot v[i] = temp }
Delete, Algorithm 3.5.9, p. 139 This algorithm deletes the root (the item with largest value) from a heap containing n elements. The array v represents the heap.
Input Parameters: v,n Output Parameters: v,n
heap_delete(v,n) { v[1] = v[n] n = n - 1 siftdown(v,1,n) }
How to Build a Heap
Heapify, Algorithm 3.5.12, p. 141 This algorithm rearranges the data in the array v , indexed from 1 to n , so that Heapsort it represents a heap.
Input Parameters: v,n Output Parameters: v
heapify(v,n) { // n/2 is the index of the parent of // the last node for i = n/2 downto 1 siftdown(v,i,n) }
Complexity? Ī(n) See p. 142
Heapsort: the Strategy