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
Properties: -The value in each node is less than all values in the node’s subtrees Min Heap
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
Insert new element (9) here, then move up
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
Insert / delete - O(h) Serves as a basis for heap sort, a very efficient sorting algorithm. Priority queues, Huffman encoding. Heap Performance & Applications
Heap as Vector Root level 2 level 3 level 4 Root Level 2 Level 3 Level 4
* 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
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
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
struct SymbolPriority { SymbolPriority(char symbol, int priority); char Symbol; int Priority; bool operator > (const SymbolPriority& compareTo); }; Tip: SymbolPriority Structure
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
Read chapter 8, prepare for quiz next class. I will randomly question 10 students. Correct answer earns 1%, incorrect earns -2%.Assignment