Download presentation
Presentation is loading. Please wait.
Published byGlenna Kurnia Modified over 6 years ago
1
Lecture 13 – Heaps Container Adapters priority_queue – impl. with heap
Max and Min Heaps push () pop () Heap Sort Heapifying (make_heap)
2
Recall: 3 Container Adapters
Priority Queues Recall: 3 Container Adapters Stack Queue Priority Queue – implementation? Stack and Queue Underlying default sequence container: deque Deque: efficient operations on front and back Priority Queue Uses <vector> – efficient only at back Maintains complete tree w/special ordering property Vector w/property is Heap
3
Complete Binary Tree All levels full except last
Last level children to left Why store tree in vector? parent (i) = p (i) = ? leftChild (i) = lc (i) = ? rightChild (i) = rc (i) = ?
4
Max and Min Heaps Heap property (Max):
Value (X) >= Value (Child (X))
5
priority_queue::push
1) v.push_back (50);
6
Upheap (restore heap property)
2) upHeap (v.size () – 1);
7
Push Code void PQ::push (const T& item) { v.push_back (item); upHeap (v.size ( ) – 1); }
8
upHeap Code void PQ::upHeap (size_t pos) { T item = v[pos]; size_t i; // Move parent down, item up for (i = pos; i != 0 && item > v[p (i)]; i = p (i)) { v[i] = v[p (i)]; // note: swap is unnecessary v[i] = item; }
9
priority_queue::pop 18 v[0] = v.back (); v.pop_back ();
10
Downheap Compare v[i] with max child Move max child up if necessary
11
Pop void PQ::pop () { // Overwrite top element with last v[0] = v.back (); v.pop_back (); // O (1) // Move elem down to proper place downHeap (0); }
12
DownHeap (helper) void PQ::downHeap (size_t pos)
{ // Move “v[pos]” down, max child up size_t i, mc; // mc is index of max child T val = v[pos]; for (i = pos; (mc = lc (i)) < v.size (); i = mc) { if (mc + 1 < v.size () && v[mc] < v[mc + 1]) ++mc; // “mc” is now referencing larger child // Compare val and ? // Move child up if necessary } // Place val in correct spot
13
Heaps O(N*lg (N)) sort in worst case
Heap Sort Overview Heaps O(N*lg (N)) sort in worst case Push all elements Retrieve and place in array back to front Naïve: 2*Sum (i =1:N) [lg(i)] OR 1) Heapify vector v STL assistance Roll our own buildHeap 2) While (N != 1) Swap largest element and back of v N-- Fix up heap property at root (downHeap)
14
Make_Heap (STL) int arr[] = { 50, 20, 75, 35, 25 }; make_heap (arr, arr + 5); // in STL // Details later on impl.- <algorithm>
15
buildHeap Start at lowest internal node: position = ? Then do
downHeap (position)
16
buildHeap Cont’d
17
Implementing Heap Sort (Swap and Fix up)
Swap front and back Do downHeap (0)
18
Heap Sort (Details) // Create heap from vector bottom-up
// Start with lowest internal node // N is taken as size of ‘v’ // ‘for’ creates heap bottom-up: O(N) for (i = (N – 2) / 2; i >= 0; i--) downHeap (i); while (N != 1) // 2 or more elements { swap (v[0], v[N-1]); N--; downHeap (0); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.