Heaps Data Structures & OO Development II 1 Computer Science Dept Va Tech August 2006 ©2006 McQuain Heaps A heap is a complete binary tree. A max-heap.

Slides:



Advertisements
Similar presentations
CS 206 Introduction to Computer Science II 03 / 23 / 2009 Instructor: Michael Eckmann.
Advertisements

CS Section 600 CS Section 002 Dr. Angela Guercio Spring 2010.
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.
CS 315 March 24 Goals: Heap (Chapter 6) priority queue definition of a heap Algorithms for Insert DeleteMin percolate-down Build-heap.
CS 206 Introduction to Computer Science II 11 / 04 / 2009 Instructor: Michael Eckmann.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
Heapsort CIS 606 Spring Overview Heapsort – O(n lg n) worst case—like merge sort. – Sorts in place—like insertion sort. – Combines the best of both.
1 Chapter 8 Priority Queues. 2 Implementations Heaps Priority queues and heaps Vector based implementation of heaps Skew heaps Outline.
Heapsort Based off slides by: David Matuszek
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
Binary Trees A binary tree is made up of a finite set of nodes that is either empty or consists of a node called the root together with two binary trees.
Compiled by: Dr. Mohammad Alhawarat BST, Priority Queue, Heaps - Heapsort CHAPTER 07.
ADT Table and Heap Ellen Walker CPSC 201 Data Structures Hiram College.
Chapter 21 Priority Queue: Binary Heap Saurav Karmakar.
CMSC 341 Binary Heaps Priority Queues. 2 Priority: some property of an object that allows it to be prioritized WRT other objects (of the same type) Priority.
Priority Queue. Priority Queues Queue (FIFO). Priority queue. Deletion from a priority queue is determined by the element priority. Two kinds of priority.
Heapsort. What is a “heap”? Definitions of heap: 1.A large area of memory from which the programmer can allocate blocks as needed, and deallocate them.
CMSC 341 Binary Heaps Priority Queues. 2 Priority: some property of an object that allows it to be prioritized WRT other objects (of the same type) Priority.
FALL 2005CENG 213 Data Structures1 Priority Queues (Heaps) Reference: Chapter 7.
CS 367 Introduction to Data Structures Lecture 8.
Lecture on Data Structures(Trees). Prepared by, Jesmin Akhter, Lecturer, IIT,JU 2 Properties of Heaps ◈ Heaps are binary trees that are ordered.
1 Priority Queues (Heaps). 2 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full sorted.
Priority Queues and Heaps. John Edgar  Define the ADT priority queue  Define the partially ordered property  Define a heap  Implement a heap using.
Priority Queues and Heaps Tom Przybylinski. Maps ● We have (key,value) pairs, called entries ● We want to store and find/remove arbitrary entries (random.
Coursenotes CS3114: Data Structures and Algorithms Clifford A. Shaffer Yang Cao Department of Computer Science Virginia Tech Copyright ©
Heaps and Heap Sort. Sorting III / Slide 2 Background: Complete Binary Trees * A complete binary tree is the tree n Where a node can have 0 (for the leaves)
Sorting With Priority Queue In-place Extra O(N) space
Priority Queues and Heaps
Heaps 8/2/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser,
Priority Queues Chuan-Ming Liu
October 30th – Priority QUeues
Binary Heaps What is a Binary Heap?
Bohyung Han CSE, POSTECH
Heap Sort Example Qamar Abbas.
Priority Queues (Heaps)
Priority Queues Linked-list Insert Æ Æ head head
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
Binary Heaps What is a Binary Heap?
Binary Heaps What is a Binary Heap?
ADT Heap data structure
7/23/2009 Many thanks to David Sun for some of the included slides!
Data Structures & Algorithms Priority Queues & HeapSort
Draw pictures to indicate the subproblems middleMax solves at each level and the resulting maxPtr and PrevPtr for each on this linked list:
CMSC 341 Lecture 14 Priority Queues & Heaps
Binary Tree Application Operations in Heaps
Tree Representation Heap.
Heaps A heap is a binary tree.
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
Computer Science 2 Heaps.
Heap Sort The Heap Data Structure
Searching CLRS, Sections 9.1 – 9.3.
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.
Heapsort.
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Heaps © 2014 Goodrich, Tamassia, Goldwasser Heaps Heaps
A Heap Implementation Chapter 26 Adapted from Pearson Education, Inc.
CSE 373 Priority queue implementation; Intro to heaps
Priority Queues (Heaps)
Heapsort.
Priority Queues & Heaps
Heaps By JJ Shepherd.
Hash Maps: The point of a hash map is to FIND DATA QUICKLY.
Chapter 12 Heap ADT © 2011 Pearson Addison-Wesley. All rights reserved.
Heapsort.
Computer Algorithms CISC4080 CIS, Fordham Univ.
Priority Queue and Heap
CO 303 Algorithm Analysis and Design
Heaps.
Priority Queues (Heaps)
CMPT 225 Lecture 16 – Heap Sort.
Presentation transcript:

Heaps Data Structures & OO Development II 1 Computer Science Dept Va Tech August 2006 ©2006 McQuain Heaps A heap is a complete binary tree. A max-heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. A min-heap is defined similarly Mapping the elements of a heap into an array is trivial: if a node is stored at index k, then its left child is stored at index 2k+1 and its right child at index 2k+2

Heaps Data Structures & OO Development II 2 Computer Science Dept Va Tech August 2006 ©2006 McQuain Building a Heap The fact that a heap is a complete binary tree allows it to be efficiently represented using a simple array. Given an array of N values, a heap containing those values can be built, in situ, by simply “sifting” each internal node down to its proper location: start with the last internal node -swap the current internal node with its larger child, if necessary -then follow the swapped node down -continue until all internal nodes are done * * * *

Heaps Data Structures & OO Development II 3 Computer Science Dept Va Tech August 2006 ©2006 McQuain Heap Class Interface We will consider a somewhat minimal heap class: template class HeapT { private: T* Hp; int numVertices; int Sz; void SiftDown(int toSift); public: HeapT(); HeapT(const T* const List, const int numItems); HeapT(const HeapT& Source); HeapT& operator=(const HeapT& Source); ~HeapT(); bool Insert(const T& Data); T RemoveRoot(); void BuildHeap(); bool isEmpty() const; bool isLeaf(int Vertex) const; int leftChild(int Vertex) const; int rightChild(int Vertex) const; int Parent(int Vertex) const; int Size() const; void Display(ostream& Out); };

Heaps Data Structures & OO Development II 4 Computer Science Dept Va Tech August 2006 ©2006 McQuain BuildHeap and SiftDown As described earlier: template void HeapT ::BuildHeap() { int Idx; for (Idx = numVertices/2 - 1; Idx >= 0; Idx--) SiftDown(Idx); } template void HeapT ::SiftDown(int toSift) { while ( !isLeaf(toSift) ) { int MaxChild = leftChild(toSift); if ( (MaxChild < numVertices - 1) && (Hp[MaxChild] < Hp[MaxChild + 1]) ) MaxChild++; if (Hp[toSift] >= Hp[MaxChild]) return; T tmpItem = Hp[toSift]; Hp[toSift] = Hp[MaxChild]; Hp[MaxChild] = tmpItem; toSift = MaxChild; } Determine which child node is larger See if node must sift down If so, swap it with its larger child (maintaining heap property), and continue sifting down… QTP:Why is Idx initialized this way?

Heaps Data Structures & OO Development II 5 Computer Science Dept Va Tech August 2006 ©2006 McQuain template void HeapT ::SiftDown(int toSift) { while ( !isLeaf(toSift) ) { int MaxChild = leftChild(toSift); if ( (MaxChild < numVertices - 1) && (Hp[MaxChild] < Hp[MaxChild + 1]) ) MaxChild++; if (Hp[toSift] >= Hp[MaxChild]) return; T tmpItem = Hp[toSift]; Hp[toSift] = Hp[MaxChild]; Hp[MaxChild] = tmpItem; toSift = MaxChild; } Cost of SiftDown In a complete binary tree of N nodes, the number of levels is at most 1 + log(N). Since each non-terminating iteration of the loop moves the target value a distance of 1 level, the loop will perform no more than log(N) iterations. Thus, the worst case cost of SiftDown() is Θ(log N). In the worst case, we perform two element comparisons… …and one element swap per iteration That’s 2log(N) comparisons and log(N) swaps.

Heaps Data Structures & OO Development II 6 Computer Science Dept Va Tech August 2006 ©2006 McQuain Cost of BuildHeap Suppose we start with a complete binary tree with N nodes; the number of steps required for sifting values down will be maximized if the tree is also full, in which case N = 2 d -1 for some integer d =  log N . For example: level 0:2 0 nodes, can sift down d - 1 levels level 1:2 1 nodes, can sift down d - 2 levels level 2:2 2 nodes, can sift down d - 3 levels We can prove that in general, level k of a full and complete binary tree will contain 2 k nodes, and that those nodes are d – k – 1 levels above the leaves. Thus…

Heaps Data Structures & OO Development II 7 Computer Science Dept Va Tech August 2006 ©2006 McQuain Cost of BuildHeap In the worst case, the number of comparisons BuildHeap() will require in building a heap of N nodes is given by: Since, at worst, there is one swap for each two comparisons, the maximum number of swaps is N –  log N . Hence, building a heap of N nodes is Θ(N) in both comparisons and swaps.

Heaps Data Structures & OO Development II 8 Computer Science Dept Va Tech August 2006 ©2006 McQuain Deleting the Root of a Heap We will see that the most common operation on a heap is the deletion of the root node. The heap property is maintained by sifting down… template T HeapT ::RemoveRoot() { if (numVertices == 0) return T(); T tmpItem = Hp[0]; Hp[0] = Hp[numVertices - 1]; Hp[numVertices - 1] = tmpItem; numVertices--; SiftDown(0); return tmpItem; } Check for empty heap Swap the root with the last leaf, and shrink the heap by one node. Sift the new root down to restore the heap property. QTP:Why is the last leaf chosen as the replacement for the root?

Heaps Data Structures & OO Development II 9 Computer Science Dept Va Tech August 2006 ©2006 McQuain Example of Root Deletion Given the initial heap: In a heap of N nodes, the maximum distance the root can sift down would be  log N 

Heaps Data Structures & OO Development II 10 Computer Science Dept Va Tech August 2006 ©2006 McQuain Cost of Deleting the Roots Recalling the earlier analysis of building a heap, level k of a full and complete binary tree will contain 2 k nodes, and that those nodes are k levels below the root level. So, when the root is deleted the maximum number of levels the swapped node can sift down is the number of the level from which that node was swapped. Thus, in the worst case, for deleting all the roots… As usual, with Heap Sort, this would entail half as many element swaps.

Heaps Data Structures & OO Development II 11 Computer Science Dept Va Tech August 2006 ©2006 McQuain Cost of Heap Sort Adding in the cost of building the heap from our earlier analysis, and... So, in the worst case, Heap Sort is  (N log N) in both swaps and comparisons.

Heaps Data Structures & OO Development II 12 Computer Science Dept Va Tech August 2006 ©2006 McQuain Heap Sort A list can be sorted by first building it into a heap, and then iteratively deleting the root node from the heap until the heap is empty. If the deleted roots are stored in reverse order in an array they will be sorted in ascending order (if a max heap is used). void HeapSort(int* List, int Size) { HeapT toSort(List, Size); toSort.BuildHeap(); int Idx = Size - 1; while ( !toSort.isEmpty() ) { List[Idx] = toSort.RemoveRoot(); Idx--; }

Heaps Data Structures & OO Development II 13 Computer Science Dept Va Tech August 2006 ©2006 McQuain Priority Queues A priority queue consists of entries, each of which contains a key field, called the priority of the entry. Aside from the usual operations of creation, clearing, tests for full and empty, and reporting its size, a priority queue has only two operations: -insertion of a new entry -removal of the entry having the largest (or smallest) key Key values need not be unique. If not, then removal may target any entry holding the largest value.

Heaps Data Structures & OO Development II 14 Computer Science Dept Va Tech August 2006 ©2006 McQuain Representation Representation of a priority queue may be achieved using: -a sorted list, but… -an unsorted list, but… -a max-heap Priority queues may be used to manage prioritized processes in a time-sharing environment, time-dependent simulations, and even numerical linear algebra.