Chapter 9 Heaps and Priority Queues. 9-2 What is a Heap? A heap is a binary tree that satisfies these special SHAPE and ORDER properties: –Its shape must.

Slides:



Advertisements
Similar presentations
COL 106 Shweta Agrawal and Amit Kumar
Advertisements

1 A full binary tree A full binary tree is a binary tree in which all the leaves are on the same level and every non leaf node has two children. SHAPE.
1 Nell Dale Chapter 9 Trees Plus Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
1 A Two-Level Binary Expression ‘-’ ‘8’ ‘5’ treePtr INORDER TRAVERSAL : has value 3 PREORDER TRAVERSAL: POSTORDER TRAVERSAL: 8 5 -
1 Heaps & Priority Queues (Walls & Mirrors - Remainder of Chapter 11)
CMPT 225 Priority Queues and Heaps. Priority Queues Items in a priority queue have a priority The priority is usually numerical value Could be lowest.
1 Chapter 6 Priority Queues (Heaps) General ideas of priority queues (Insert & DeleteMin) Efficient implementation of priority queue Uses of priority queues.
CS 315 March 24 Goals: Heap (Chapter 6) priority queue definition of a heap Algorithms for Insert DeleteMin percolate-down Build-heap.
heaps1 Trees IV: The Heap heaps2 Heap Like a binary search tree, a heap is a binary tree in which the data entries can be compared using total order.
1 C++ Plus Data Structures Nell Dale Chapter 10 Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
Priority Queues, Heaps CS3240, L. grewe 1. 2 Goals Describe a priority queue at the logical level and implement a priority queue as a list Describe the.
Heaps CS 308 – Data Structures.
1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
CS 261 – Data Structures Priority Queues & Heaps.
C++ Plus Data Structures
Source: Muangsin / Weiss1 Priority Queue (Heap) A kind of queue Dequeue gets element with the highest priority Priority is based on a comparable value.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County.
9 Priority Queues, Heaps, and Graphs. 9-2 What is a Heap? A heap is a binary tree that satisfies these special SHAPE and ORDER properties: –Its shape.
1 Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Heaps and Priority Queues CS 3358 – Data Structures.
Compiled by: Dr. Mohammad Alhawarat BST, Priority Queue, Heaps - Heapsort CHAPTER 07.
Computer Science and Software Engineering University of Wisconsin - Platteville 12. Heap Yan Shi CS/SE 2630 Lecture Notes Partially adopted from C++ Plus.
PRIORITY QUEUES (HEAPS). Queues are a standard mechanism for ordering tasks on a first-come, first-served basis However, some tasks may be more important.
© 2011 Pearson Addison-Wesley. All rights reserved 11 B-1 Chapter 11 (continued) Trees.
Chapter 9 Priority Queues, Heaps, Graphs, and Sets.
Chapter 9 Priority Queues, Heaps, and Graphs. 2 Goals Describe a priority queue at the logical level and implement a priority queue as a list Describe.
data ordered along paths from root to leaf
Chapter 9 Priority Queues, Heaps, Graphs 1 Fall 2010.
COSC2007 Data Structures II Chapter 12 Tables & Priority Queues III.
Ceng-112 Data Structures I Figure 9-1 The heap is guaranteed to hold the largest node of the tree in the root. The smaller nodes of a heap can be.
Algorithms and data structures Protected by
Priority Queues (Heaps)
CPSC 252 Binary Heaps Page 1 Binary Heaps A complete binary tree is a binary tree that satisfies the following properties: - every level, except possibly.
CE 221 Data Structures and Algorithms Chapter 6: Priority Queues (Binary Heaps) Text: Read Weiss, §6.1 – 6.3 1Izmir University of Economics.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
Intro. to Data Structures Chapter 6 Priority Queue (Heap) Veera Muangsin, Dept. of Computer Engineering, Chulalongkorn University 1 Priority Queue.
Sorting Dr. Yingwu Zhu. Heaps A heap is a binary tree with properties: 1. It is complete Each level of tree completely filled Except possibly bottom level.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
FALL 2005CENG 213 Data Structures1 Priority Queues (Heaps) Reference: Chapter 7.
AVL Trees and Heaps. AVL Trees So far balancing the tree was done globally Basically every node was involved in the balance operation Tree balancing can.
CSI 312 Dr. Yousef Qawqzeh Heaps and Priority Queue.
Sorting and Searching Algorithms CS Sorting means... l The values stored in an array have keys of a type for which the relational operators are.
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 Binary Heaps What if we’re mostly concerned with finding the most relevant data?  A binary heap is a binary tree (2 or fewer subtrees for each node)
Heaps CS 302 – Data Structures Sections 8.8, 9.1, and 9.2.
Chapter 9 Heaps and Priority Queues Lecture 18. Full Binary Tree Every non-leaf node has two children Leaves are on the same level Full Binary Tree.
Course: Programming II - Abstract Data Types HeapsSlide Number 1 The ADT Heap So far we have seen the following sorting types : 1) Linked List sort by.
1 Priority Queues (Heaps). 2 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full sorted.
CS 201 Data Structures and Algorithms
Heaps (8.3) CSE 2011 Winter May 2018.
C++ Plus Data Structures
Source: Muangsin / Weiss
Priority Queues Linked-list Insert Æ Æ head head
Heap Chapter 9 Objectives Upon completion you will be able to:
Chapter 9 Priority Queues, Heaps, Graphs, and Sets
Sorting means The values stored in an array have keys of a type for which the relational operators are defined. (We also assume unique keys.) Sorting.
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
CE 221 Data Structures and Algorithms
C++ Plus Data Structures
Binary Heaps What if we’re mostly concerned with finding the most relevant data? A binary heap is a binary tree (2 or fewer subtrees for each node) A heap.
Chapter 9 Priority Queues and Sets
Heaps and Priority Queues
Chapter 10 Sorting Algorithms
C++ Plus Data Structures
Chapter 9 The Priority Queue ADT
Heaps.
Presentation transcript:

Chapter 9 Heaps and Priority Queues

9-2 What is a Heap? A heap is a binary tree that satisfies these special SHAPE and ORDER properties: –Its shape must be a complete binary tree. –For each node in the heap, the value stored in that node is greater than or equal to the value in each of its children.

9-3 Are these Both Heaps? C A T treePtr

9-4 Is this a Heap? tree

9-5 Where is the Largest Element in a Heap Always Found? tree

9-6 We Can Number the Nodes Left to Right by Level This Way tree

9-7 And use the Numbers as Array Indexes to Store the Trees tree [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes

9-8 // HEAP SPECIFICATION struct HeapType { void ReheapDown ( int root, int bottom ) ; void ReheapUp ( int root, int top ) ; int* elements; //ARRAY to be allocated dynamically int numElements ; };

9-9 Maintaining Heap When we delete an element from the heap, we have to copy a node from the bottom in its place to maintain the shape But the heap loses its order property We must swap elements until we fix this problem Consider the problem shown in the next slides when the root node is deleted

9-10

9-11

9-12 ReHeapDown We call the function ReHeapDown that pushes down the element that violates the heap order property until the problem is fixed It is a recursive function that takes the index of the current node in violation and the index of the bottom element The Heap is to be fixed between the current node and the bottom element

9-13 ReHeapDown Each time ReHeapDown is called, we go down one level thus we satisfy the smaller caller criterea for recursion There are two base cases where we stop: –If elements[root] is a leaf –If heap order property is satisfied

9-14 ReheapDown // IMPLEMENTATION OF RECURSIVE HEAP MEMBER FUNCTIONS void HeapType::ReheapDown ( int root, int bottom ) // Pre: root is the index of the node that may violate the // heap order property // Post: Heap order property is restored between root and bottom { int maxChild ; int rightChild ; int leftChild ; leftChild = root * ; rightChild = root * ;

9-15 ReheapDown (cont) if ( leftChild <= bottom ) // ReheapDown continued { if ( leftChild == bottom ) maxChild = leftChld ; else { if (elements [ leftChild ] <= elements [ rightChild ] ) maxChild = rightChild ; else maxChild = leftChild ; } if ( elements [ root ] < elements [ maxChild ] ) { Swap ( elements [ root ], elements [ maxChild ] ) ; ReheapDown ( maxChild, bottom ) ; }

9-16 At the End of the Second Iteration of the Loop

9-17 ReHeapUp This function is converse of ReHeapDown It takes a leaf node that violates the order property and moves it up until its correct position is found Each node’s value should be compared to the value of its parent and then it should be moved up if parent is smaller

// IMPLEMENTATIONcontinued void HeapType::ReheapUp ( int root, int top ) // Pre: root is the index of the node that may violate the heap // order property. The order property is satisfied from top to // next-to-last node. // Post: Heap order property is restored between root and top //Comment: The parameters passed to this function are now correct { int parent ; if ( root > top ) //If we have not reached top yet { parent = ( root - 1 ) / 2; if ( elements [ parent ] < elements [ root ] ) { Swap ( elements [ parent ], elements [ root ] ) ; ReheapUp ( parent,top ) ; //climb up } 18

9-19 Priority Queue A priority queue is an ADT with the property that only the highest-priority element can be accessed at any time.

9-20 ADT Priority Queue Operations Transformers –MakeEmpty –Enqueue –Dequeue Observers –IsEmpty –IsFull change state observe state

9-21 Implementation Level There are many ways to implement a priority queue –An unsorted List- dequeuing would require searching through the entire list –An Array-Based Sorted List- Enqueuing is expensive –A Reference-Based Sorted List- Enqueuing again is 0(N) –A Binary Search Tree- On average, 0(log 2 N) steps for both enqueue and dequeue –A Heap- guarantees 0(log 2 N) steps, even in the worst case

9-22 PQType ~PQType Enqueue Dequeue. [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] ‘X’ ‘C’ ‘J’ Private Data: numItems 3 maxItems 10 items.elements.numElements class PQType

9-23 Class PQType Declaration class FullPQ(){}; class EmptyPQ(){}; class PQType { public: PQType(int); ~PQType(); void MakeEmpty(); bool IsEmpty() const; bool IsFull() const; void Enqueue(int newItem); void Dequeue(int& item); private: int length; HeapType items; int maxItems; };

9-24 Class PQType Function Definitions PQType::PQType(int max) { maxItems = max; items.elements = new ItemType[max]; length = 0; } void PQType::MakeEmpty() { length = 0; } PQType::~PQType() { delete [] items.elements; }

9-25 Class PQType Function Definitions Dequeue Set item to root element from queue Move last leaf element into root position Decrement length items.ReheapDown(0, length-1) Enqueue Increment length Put newItem in next available position items.ReheapUp(0, length-1)

9-26 Code for Dequeue void PQType::Dequeue(int& item) { if (length == 0) throw EmptyPQ(); else { item = items.elements[0]; items.elements[0] = items.elements[length-1]; length--; items.ReheapDown(0, length-1); }

9-27 Code for Enqueue void PQType::Enqueue(int newItem) { if (length == maxItems) throw FullPQ(); else { length++; items.elements[length-1] = newItem; items.ReheapUp(0, length-1); }

9-28 Comparison of Priority Queue Implementations EnqueueDequeue HeapO(log 2 N) Linked ListO(N) Binary Search Tree BalancedO(log 2 N) SkewedO(N)