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.

Slides:



Advertisements
Similar presentations
DATA STRUCTURES AND ALGORITHMS Lecture Notes 9 Prepared by İnanç TAHRALI.
Advertisements

COL 106 Shweta Agrawal and Amit Kumar
Heaps1 Part-D2 Heaps Heaps2 Recall Priority Queue ADT (§ 7.1.3) A priority queue stores a collection of entries Each entry is a pair (key, value)
CMSC 341 Binary Heaps Priority Queues. 8/3/2007 UMBC CSMC 341 PQueue 2 Priority Queues Priority: some property of an object that allows it to be prioritized.
Heaps, Heap Sort, and Priority Queues. Sorting III / Slide 2 Background: Binary Trees * Has a root at the topmost level * Each node has zero, one or two.
Heaps, Heap Sort, and Priority Queues
Priority Queue (Heap) & Heapsort COMP171 Fall 2006 Lecture 11 & 12.
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.
Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on Binary Heaps: enqueue dequeue deleting an.
CS 315 Lecture 15 March 31 Goals Complete heap operations review insert, deletemin decreaseKey, increaseKey heap building Heap sorting Some applications.
Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on Binary Heaps: enqueue dequeue deleting an.
Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on MinHeap: Insert Delete Converting an array.
CS 315 Lecture 18 Nov 15 Goals Complete heap operations review insert, deletemin decreaseKey, increaseKey heap building Heap sorting Some applications.
Priority Queues. Container of elements where each element has an associated key A key is an attribute that can identify rank or weight of an element Examples.
Source: Muangsin / Weiss1 Priority Queue (Heap) A kind of queue Dequeue gets element with the highest priority Priority is based on a comparable value.
Lecture 11 Binary Heap King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
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 Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on Binary Heaps: enqueue dequeue deleting.
1 BST Trees A binary search tree is a binary tree in which every node satisfies the following: the key of every node in the left subtree is.
CSC 172 DATA STRUCTURES. Priority Queues Model Set with priorities associatedwith elements Priorities are comparable by a < operator Operations Insert.
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.
CS 146: Data Structures and Algorithms June 23 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
The Binary Heap. Binary Heap Looks similar to a binary search tree BUT all the values stored in the subtree rooted at a node are greater than or equal.
Chapter 21 Binary Heap.
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.
WEEK 3 Leftist Heaps CE222 Dr. Senem Kumova Metin CE222_Dr. Senem Kumova Metin.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 8 Prepared by İnanç TAHRALI.
1 Joe Meehean.  We wanted a data structure that gave us... the smallest item then the next smallest then the next and so on…  This ADT is called a priority.
Priority Queues (Heaps)
Review for Exam 2 Topics covered (since exam 1): –Splay Tree –K-D Trees –RB Tree –Priority Queue and Binary Heap –B-Tree For each of these data structures.
CE 221 Data Structures and Algorithms Chapter 6: Priority Queues (Binary Heaps) Text: Read Weiss, §6.1 – 6.3 1Izmir University of Economics.
Heaps Priority Queues. 1/6/2016Data Structure: Heaps2 Outline Binary heaps Binomial queues Leftist heaps.
Lecture 8 : Priority Queue Bong-Soo Sohn Assistant Professor School of Computer Science and Engineering Chung-Ang University.
Intro. to Data Structures Chapter 6 Priority Queue (Heap) Veera Muangsin, Dept. of Computer Engineering, Chulalongkorn University 1 Priority Queue.
FALL 2005CENG 213 Data Structures1 Priority Queues (Heaps) Reference: Chapter 7.
1 Heap Sort. A Heap is a Binary Tree Height of tree = longest path from root to leaf =  (lgn) A heap is a binary tree satisfying the heap condition:
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.
CS 367 Introduction to Data Structures Lecture 8.
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.
1 Priority Queues (Heaps)  Sections 6.1 to Priority Queues  Regular queues which supports –First In, First Out –Enqueue(): add a new element.
1 Priority Queues (Heaps). 2 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full sorted.
Heaps and Priority Queues What is a heap? A heap is a binary tree storing keys at its internal nodes and satisfying the following properties:
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)
CS 201 Data Structures and Algorithms
Priority Queues (Heaps)
Binary Heaps Priority Queues
Source: Muangsin / Weiss
Binary Heaps What is a Binary Heap?
CMSC 341 Lecture 13 Leftist Heaps
Heaps, Heap Sort, and Priority Queues
Priority Queues (Heaps)
Binary Heaps What is a Binary Heap?
Binary Heaps What is a Binary Heap?
Heaps, Heap Sort, and Priority Queues
CMSC 341: Data Structures Priority Queues – Binary Heaps
Binary Heaps Priority Queues
Heapsort Heap & Priority Queue.
Topics covered (since exam 1):
CMSC 341 Lecture 14 Priority Queues & Heaps
BuildHeap The general algorithm is to place the N keys in an array and consider it to be an unordered binary tree. The following algorithm will build a.
Binary Heaps Priority Queues
CMSC 341 Binary Search Trees.
Heap Sort The Heap Data Structure
CE 221 Data Structures and Algorithms
Heaps Priority Queues.
CMSC 341 Binary Search Trees.
Heap code in C++ template <class eType>
CMSC 341 Lecture 19.
Priority Queues (Heaps)
Presentation transcript:

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 Queue: homogeneous collection of Comparables with the following operations (duplicates are allowed) –void insert (const Comparable &x) –void deleteMin( ) –void deleteMin ( Comparable & min) –const Comparable &findMin( ) const –Construct from a set of initial values –bool isEmpty( ) const –bool isFull( ) const –void makeEmpty( )

3 Priority Queue Applications Printer management: the shorter document on the printer queue, the higher its priority. Jobs queue: users’ tasks are given priorities. System priority high. Simulations Sorting

4 Possible Implementations Use a sorted list. Sort by priority upon insertion. –findMin( ) --> Itr.retrieve( ) –insert( ) --> list.insert( ) –deleteMin( )--> list.delete( 1 ) Use ordinary BST –findMin( ) --> tree.findMin( ) –insert( ) --> tree.insert( ) –deleteMin( )--> tree.delete( tree.findMin( ) ) Use balanced BST –guaranteed O(lg n) for Red-Black

5 Binary Heap A binary heap is a Complete Binary Tree (CBT) with the further property that at every node neither child is smaller than (or equivalently, both children are at least as large as) the value in that node. This property is called a partial ordering. As a result of this partial ordering, every path from the root to a leaf visits nodes in a non-decreasing order.

6 Binary Heap Performance Performance –constructionO( n ) –findMinO( 1 ) –insertO( lg n ) –deleteMinO( lg n ) Heap efficiency results, in part, from the implementation –conceptually a complete binary tree –implementation in an array/vector (in level order) with the root at index 1

7 Binary Heap Properties For a node at index i –its left child is at index 2i –its right child is at index 2i+1 –its parent is at index  i/2  No pointer storage Fast computation of 2i and  i/2  i << 1 = 2i i >> 1 =  i/2 

8 BinaryHeap.H template class Binary Heap { public: explicit BinaryHeap(int capacity = BIG); bool isEmpty() const; bool isFull() const; const Comparable & findMin() const; void insert (const Comparable & x); void deleteMin(); void deleteMin(Comparable & min_item); void makeEmpty(); private: int currentSize; vector array; void buildHeap(); void percolateDown(int hole); };

9 BinaryHeap.C template const Comparable & BinaryHeap::findMin( ) { if ( isEmpty( ) ) throw Underflow( ); return array[1]; }

10 Insert Operation Must maintain –CBT property (heap shape): easy, just insert new element at “the right” of the array –Heap order could be wrong after insertion if new element is smaller than its ancestors continuously swap the new element with its parent until parent is not greater than it –called sift up or percolate up Performance of insert is O( lg n ) in the worst case because the height of a CBT is O( lg n )

11 BinaryHeap.C (cont) template void BinaryHeap :: insert(const Comparable & x) { if (isFull()) throw OverFlow(); int hole = ++currentSize; // percolate up for (; hole > 1 && x < array[hole/2]; hole /= 2) array[hole] = array[hole/2]; // put x in hole array[hole] = x; }

12 Deletion Operation Steps –remove min element (the root) –maintain heap shape – maintain heap order To maintain heap shape, actual node removed is “last one” in the array –replace root value with value from last node and delete last node –sift-down the new root value continually exchange value with the smaller child until no child is smaller

13 BinaryHeap.C (cont) template void BinaryHeap :: deleteMin(Comparable & minItem) { if ( isEmpty( ) ) throw Underflow( ); minItem = array[1]; array[1] = array[currentSize--]; percolateDown(1); }

14 BinaryHeap.C (cont) template void BinaryHeap ::percolateDown(int hole) { int child; Comparable tmp = array[hole]; for (; hole * 2 <= currentSize; hole = child) { child= hole * 2; if (child != currentSize && array[child + 1] < array[ child ] ) child++; if (array [child] < tmp) array[ hole ] = array[ child ]; else break; } array[hole] = tmp; }

15 Constructing a Binary Heap A BH can be constructed in O(n) time. Suppose we are given an array of objects in an arbitrary order. Since it’s an array with no holes, it’s already a CBT. It can be put into heap order in O(n) time. –Create the array and store n elements in it in arbitrary order. O(n) to copy all the objects. –Heapify the array start at ndode i =  n/2  –percolateDown(i) repeat for all nodes from i down to 1 (the root)

16 BinaryHeap.C (cont) template void BinaryHeap :: buildHeap( ) { for(int i = currentSize/2; i >0; i--) percolateDown(i); }

17 Performance of Construction A CBT has 2 h-1 nodes on level h-1. On level h-l, at most 1 swap is needed per node. On level h-2, at most 2 swaps are needed. … On level 0, at most h swaps are needed. Number of swaps = S = 2 h *0 + 2 h-1 *1 + 2 h-2 *2 + … *h = = h(2 h+1 -1) - ((h-1)2 h+1 +2) = 2 h+1 (h-(h-1))-h-2 = 2 h+1 -h-2

18 Performance of Construction (cont) But 2 h+1 -h-2= O(2 h ) But n = … + 2 h = Therefore, n = O(2 h ) So S = O(n) A heap of n nodes can be built in O(n) time.

19 Heap Sort Given n values, can sort in O(n log n) time (in place). –Insert values into array -- O(n) –heapify -- O(n) –repeatedly delete min -- O(lg n), n times Using a min heap, this code sorts in reverse order. With a max heap, it sorts in normal order. for (i = n-1; i >= 1; i--) { x =findMin(); deleteMin(); A[i+1] = x; }

20 Limitations Binary heaps support insert, findMin, deleteMin, and construct efficiently. They do not efficiently support the meld or merge operation in which 2 PQs are merged into one. If P 1 and P 2 are of size n 1 and n 2, then the merge is in O(n 1 + n 2 )

21 Leftist Heap Supports –findMin-- O(1) –deleteMin-- O(lg n) –insert-- O(lg n) –construct-- O(n) –merge-- O(lg n)

22 Leftist Tree The null path length (npl) of a node, X, is the length of the shortest path from X to a node without two children (a non-full node). An LT is a binary tree in which at each node X, the null path length of X’s right child is not larger than the null path length of the X’s left child. I.e The length of the path from X’s right child to its nearest non-full node is not larger than the length of the path from X’s left child to its nearest non-full node. An important property of leftist trees: –At every node, the shortest path to a non-full node is along the rightmost path. –Suppose this was not true. Then, at the same node the path on the left would be shorter than the path on the right.

23 Leftist Heap A leftist heap is a leftist tree in which the values in the nodes obey heap order (the tree is partially ordered). Since a LH is not necessarily a CBT we do not implement it in an array. An explicit tree implementation is used. Operations –findMin-- return root value, same as BH –deleteMin -- done using meld operation –insert-- done using meld operation –construct -- done using meld operation

24 Meld Algorithm: Meld (H1, H2) { if (!root(H1) || (root_value(H1) > root_value(H2) ) swap (H1, H2) if (root(H1) != NULL)) right(H1) <-- Meld(right(H1),H2) if (left_length(H1) < right_length(H1) swap(left(H1), right(H1); }

25 Meld (cont) Performance:O( lg n ) –the rightmost path of each tree has at most  lg(n+1)  nodes. So O( lg n ) nodes will be involved.

26

27

28

29 Leftist Heap Operations Other operations implemented in terms of Meld –insert (item) make item into a 1-node LH, X Meld(*this, X) –deleteMin Meld(left subtree, right subtree) –construct from N items make N LHs from the N values, one element in each meld each in –one at a time : –use queue and build pairwise :

30 LH Construct Algorithm: –make N leftist heaps, H 1 ….H N each with one data value –Instantiate Queue Q; –for (I = 1; I <= N; I++) Q.Enqueue(H i ); –Heap H = Q.Dequeue( ); –while (!Q.IsEmpty( ) ) Q.Enqueue( meld( H, Q.Dequeue( ) ) ); H = Q.Dequeue( );