Download presentation
Presentation is loading. Please wait.
Published byNathan Taylor Modified over 9 years ago
1
Properties: -The value in each node is greater than all values in the node’s subtrees -Complete tree! (fills up from left to right) Max Heap
2
Properties: -The value in each node is less than all values in the node’s subtrees Min Heap
3
1.Insert the new item in the next position at the bottom of the heap (i.e. at the last row). 2.While the new item is not at the root and the new item is larger than its parent - Swap the new item’s value with its parent value thus moving the new item up the heap. Inserting into Max Heap
4
10 6 3 2 7 9 Insert new element (9) here, then move up
5
Only the top element can be removed from the heap! 1.Remove the heap root and replace it with the rightmost item in the heap. 2.While the new root value has children and its value is smaller than the value of either of its children - Swap the new item’s value with its child value thus moving the new item down the heap. Removing from Max Heap
6
Insert / delete - O(h) Serves as a basis for heap sort, a very efficient sorting algorithm. Priority queues, Huffman encoding. Heap Performance & Applications
7
Heap as Vector 100193617325127 Root level 2 level 3 level 4 Root Level 2 Level 3 Level 4
8
* Highest-priority element is always at the top of queue. * New elements are inserted in the order of priority. * Can pop only the element at the top of the queue. Priority Queue
9
First insert the new element at the end of the priority queue vector then… child = vector.size() – 1 parent = (child – 1)/2 while ( parent >= 0 and vector[parent] < vector[child] ) { parent = (child – 1)/2; swap(vector[parent], vector[child]); child = parent; } Priority Queue: Insert Algorithm
10
Write a program that: -Reads a sentence from cin -Calculates occurrences (i.e. the weight) of each character in the sentence -Stores occurrences of each character in the queue such that the characters with lowest occurrence are stored first Exercise: Priority Queue
11
struct SymbolPriority { SymbolPriority(char symbol, int priority); char Symbol; int Priority; bool operator > (const SymbolPriority& compareTo); }; Tip: SymbolPriority Structure
12
template class PriorityQueue { public: PriorityQueue(); const T& Top() const; bool IsEmpty() const; void Pop(); void Push(const T& value); private: vector QueueData; }; Tip: PriorityQueue Class
13
Read chapter 8, prepare for quiz next class. I will randomly question 10 students. Correct answer earns 1%, incorrect earns -2%.Assignment
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.