110 likes | 224 Views
Heaps. CIS 237 – Data Structures. Array Based Trees. Complete full to h-1 filled at level h from left to right Stored as an vector, root in position 0 For the node at position i left child at 2i + 1 right child at 2i + 2 For a node at i the parent is at
E N D
Heaps CIS 237 – Data Structures
Array Based Trees • Complete • full to h-1 • filled at level h from left to right • Stored as an vector, root in position 0 • For the node at position i • left child at 2i + 1 • right child at 2i + 2 • For a node at i the parent is at • For n nodes in the heap, the first leaf is at
78 15 32 5 10 20 0 1 2 3 4 5 78 15 32 5 10 20 Example
Heap Definition • A binary tree • Complete • Max-Heap • the key value at each node is greater than its children • Min-Heap • the key value at each node is less than its children
78 v[0] 35 32 v[1] v[2] 5 10 20 19 v[3] v[4] v[5] v[6] 1 3 7 8 v[7] v[9] v[10] v[8] Heap Algorithms - Insert • Heap is a vector • Add by with push back • Restore heap order (reheapify)
reheapify Algorithm • New value is pushed back and then moved to the appropriate location • v.push_back(value); • currentPos = last -1 • parentPos = (currentPos-1)/2 • target = v[last-1] • while (currentPos != 0) • 1. if (target > v[parentPos]) • 1. v[currentPos] = v[parentPos] • 2. currentPos = parentPos • 3. parentPos = (currentPos-1)/2 • 2. else • 1. break; //all moves done • 3. end if • end while • v[currentPos] = target
78 v[0] 35 32 v[1] v[2] 5 10 20 19 v[3] v[4] v[5] v[6] 1 3 7 8 v[7] v[9] v[10] v[8] Heap Algorithms – Delete • Root always deleted • Exchange root and last element • “Cut off” last element • Pushes new root down to proper place
Adjust Algorithm • //Determine which child has the larger key • currentPos = 0 • target = heap[0] • childPos = 2 * currentPos + 1 • while (childPos <= last-1) //there is a left child • if childPos+1 <= last-1 then //there is a right child too • if v[childPos+1] > v[childPos] //right child bigger • childPos = childPos +1 //use the right child • end if • end if • ///Check for child being larger than parent….
Delete continued • if v[childPos] > target //bigger than value so move up • v[currentPos] = v[childPos] • currentPos = childPos • childPos = 2 * currentPos + 1 • else • break //done • end if • end while • v[currentPos] = target
Pop Heap temp = v[0] v[0] = v[last-1] adjustHeap(v, 0, last-1) return temp
Heapifying a Vector • Start with the last non-leaf (position: n/2 -1) • adjustHeap(v, position, last-1) • Decrement position and adjust again