CMSC 341. Binary Heaps. Priority Queues

Similar documents
CMSC 341 Priority Queues & Heaps. Based on slides from previous iterations of this course

CE 221 Data Structures and Algorithms

Priority Queues. Binary Heaps

Priority Queues (Heaps)

CMSC 341 Lecture 14: Priority Queues, Heaps

Data Structures. Giri Narasimhan Office: ECS 254A Phone: x-3748

Priority Queues (Heaps)

COMP : Trees. COMP20012 Trees 219

CMSC 341 Lecture 15 Leftist Heaps

CMSC 341 Lecture 15 Leftist Heaps

Priority Queues. e.g. jobs sent to a printer, Operating system job scheduler in a multi-user environment. Simulation environments

CMSC 341 Leftist Heaps

Heaps, Heap Sort, and Priority Queues.

Heaps. Heaps. A heap is a complete binary tree.

CS 315 April 1. Goals: Heap (Chapter 6) continued review of Algorithms for Insert DeleteMin. algoritms for decrasekey increasekey Build-heap

CS350: Data Structures Heaps and Priority Queues

Chapter 6 Heaps. Introduction. Heap Model. Heap Implementation

Heap Model. specialized queue required heap (priority queue) provides at least

CS 234. Module 8. November 15, CS 234 Module 8 ADT Priority Queue 1 / 22

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof.

Figure 1: A complete binary tree.

CSCI2100B Data Structures Heaps

3. Priority Queues. ADT Stack : LIFO. ADT Queue : FIFO. ADT Priority Queue : pick the element with the lowest (or highest) priority.

Priority Queues Heaps Heapsort

Arrays aren t going to work. What can we do? Use pointers Copy a large section of a heap, with a single pointer assignment

Readings. Priority Queue ADT. FindMin Problem. Priority Queues & Binary Heaps. List implementation of a Priority Queue

Data Structures and Algorithms

Algorithms and Data Structures

Priority Queues Heaps Heapsort

Binary Heaps. COL 106 Shweta Agrawal and Amit Kumar

Data Structures Week #8. Heaps (Priority Queues)

Data Structures and Algorithms

Binary Heaps. CSE 373 Data Structures Lecture 11

Sorting and Searching

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

Priority Queues. 04/10/03 Lecture 22 1

INF2220: algorithms and data structures Series 4

Priority Queues. Lecture15: Heaps. Priority Queue ADT. Sequence based Priority Queue

Today s Outline. The One Page Cheat Sheet. Simplifying Recurrences. Set Notation. Set Notation. Priority Queues. O( 2 n ) O( n 3 )

CSE 214 Computer Science II Heaps and Priority Queues

Programming II (CS300)

Sorting and Searching

Priority Queues and Binary Heaps. See Chapter 21 of the text, pages

The priority is indicated by a number, the lower the number - the higher the priority.

CSCI-1200 Data Structures Fall 2018 Lecture 23 Priority Queues II

Priority Queues. Binary Heaps

Priority Queues and Binary Heaps. See Chapter 21 of the text, pages

Maintain binary search tree property nodes to the left are less than the current node, nodes to the right are greater

Figure 1: A complete binary tree.

Binary heaps (chapters ) Leftist heaps

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example.

The beautiful binary heap.

Data Structures Lesson 9

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

Recall: Properties of B-Trees

Overview of Presentation. Heapsort. Heap Properties. What is Heap? Building a Heap. Two Basic Procedure on Heap

Sorted Arrays. Operation Access Search Selection Predecessor Successor Output (print) Insert Delete Extract-Min

Administration CSE 326: Data Structures

Properties of a heap (represented by an array A)

CSE373: Data Structures & Algorithms Lecture 9: Priority Queues and Binary Heaps. Linda Shapiro Spring 2016

Data Structures and Algorithms for Engineers

07 B: Sorting II. CS1102S: Data Structures and Algorithms. Martin Henz. March 5, Generated on Friday 5 th March, 2010, 08:31

Learning Goals. CS221: Algorithms and Data Structures Lecture #3 Mind Your Priority Queues. Today s Outline. Back to Queues. Priority Queue ADT

Implementations. Priority Queues. Heaps and Heap Order. The Insert Operation CS206 CS206

Red-Black Trees. Based on materials by Dennis Frey, Yun Peng, Jian Chen, and Daniel Hood

CMSC 341. Binary Search Trees CMSC 341 BST

CMSC 341 Lecture 10 Binary Search Trees

CS102 Binary Search Trees

Priority Queues and Binary Heaps

CS S-08 Priority Queues Heaps 1

Trees. (Trees) Data Structures and Programming Spring / 28

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs

CSE373: Data Structures & Algorithms Lecture 9: Priority Queues and Binary Heaps. Nicki Dell Spring 2014

csci 210: Data Structures Priority Queues and Heaps

Multi-way Search Trees. (Multi-way Search Trees) Data Structures and Programming Spring / 25

Review: Trees Binary Search Trees Sets in Java Collections API CS1102S: Data Structures and Algorithms 05 A: Trees II

CSE 373: Data Structures and Algorithms

Priority Queues and Heaps. Heaps of fun, for everyone!

9. Heap : Priority Queue

Topic: Heaps and priority queues

Programming II (CS300)

Advanced Algorithms. Class Notes for Thursday, September 18, 2014 Bernard Moret

Heapsort. Heap data structure

Data Structures and Algorithms

CS350: Data Structures Binary Search Trees

Priority Queues, Heaps, and Heapsort

Week 10. Sorting. 1 Binary heaps. 2 Heapification. 3 Building a heap 4 HEAP-SORT. 5 Priority queues 6 QUICK-SORT. 7 Analysing QUICK-SORT.

Trees. A tree is a directed graph with the property

Heaps Outline and Required Reading: Heaps ( 7.3) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

Priority queues. Priority queues. Priority queue operations

Data Structures and Algorithms

Lecture Notes for Advanced Algorithms

CmpSci 187: Programming with Data Structures Spring 2015

Comparisons. Θ(n 2 ) Θ(n) Sorting Revisited. So far we talked about two algorithms to sort an array of numbers. What is the advantage of merge sort?

Lecture 13: AVL Trees and Binary Heaps

Operations on Heap Tree The major operations required to be performed on a heap tree are Insertion, Deletion, and Merging.

Collection of priority-job pairs; priorities are comparable.

Week 10. Sorting. 1 Binary heaps. 2 Heapification. 3 Building a heap 4 HEAP-SORT. 5 Priority queues 6 QUICK-SORT. 7 Analysing QUICK-SORT.

Comparisons. Heaps. Heaps. Heaps. Sorting Revisited. Heaps. So far we talked about two algorithms to sort an array of numbers

Heaps Goodrich, Tamassia. Heaps 1

Transcription:

CMSC 341 Binary Heaps Priority Queues

Priority Queues Priority: some property of an object that allows it to be prioritized with respect to other objects of the same type Min Priority Queue: homogeneous collection of Comparables with the following operations (duplicates are allowed). Smaller value means higher priority. void insert (Comparable x) void deletemin( ) void deletemin ( Comparable min) Comparable findmin( ) Construct from a set of initial values boolean isempty( ) boolean isfull( ) void makeempty( ) 8/3/2007 UMBC CSMC 341 PQueue 2

Priority Queue Applications Printer management: The shorter document on the printer queue, the higher its priority. Jobs queue within an operating system: Users tasks are given priorities. System priority high. Simulations The time an event happens is its priority. Sorting (heap sort) An elements value is its priority. 8/3/2007 UMBC CSMC 341 PQueue 3

Possible Implementations Use a sorted list. Sorted by priority upon insertion. findmin( ) --> list.front( ) insert( ) --> list.insert( ) deletemin( ) --> list.erase( list.begin( ) ) Use ordinary BST findmin( ) --> tree.findmin( ) insert( ) --> tree.insert( ) deletemin( ) --> tree.delete( tree.findmin( ) ) Use balanced BST guaranteed O(lg n) for Red-Black 8/3/2007 UMBC CSMC 341 PQueue 4

Min Binary Heap A min binary heap is a complete binary tree with the further property that at every node neither child is smaller than the value in that node (or equivalently, both children are at least as large as 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 nondecreasing order. What other properties of the Min Binary Heap result from this property? 8/3/2007 UMBC CSMC 341 PQueue 5

Min Binary Heap Performance Performance (n is the number of elements in the heap) construction O( n ) findmin O( 1 ) insert O( lg n ) deletemin O( 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 8/3/2007 UMBC CSMC 341 PQueue 6

Min 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 by bit shifting i << 1 = 2i i >> 1 = i/2 8/3/2007 UMBC CSMC 341 PQueue 7

Heap is a Complete Binary Tree 8/3/2007 UMBC CSMC 341 PQueue 8

Which satisfies the properties of a Heap? 8/3/2007 UMBC CSMC 341 PQueue 9

Min BinaryHeap Definition public class BinaryHeap<AnyType extends Comparable<? super AnyType>> { public BinaryHeap( ) { /* See online code */ } public BinaryHeap( int capacity ){ /* See online code */ } public BinaryHeap( AnyType [ ] items ){/* Figure 6.14 */ } public void insert( AnyType x ) { /* Figure 6.8 */ } public AnyType findmin( ) { /* TBD */ } public AnyType deletemin( ) { /* Figure 6.12 */ } public boolean isempty( ) { /* See online code */ } public void makeempty( ) { /* See online code */ } private static final int DEFAULT_CAPACITY = 10; private int currentsize; // Number of elements in heap private AnyType [ ] array; // The heap array } private void percolatedown( int hole ){/* Figure 6.12 */ } private void buildheap( ) { /* Figure 6.14 */ } private void enlargearray(int newsize){/* code online */} 8/3/2007 UMBC CSMC 341 PQueue 10

Min BinaryHeap Implementation public AnyType findmin( ) { if ( isempty( ) ) throw Underflow( ); return array[1]; } 8/3/2007 UMBC CSMC 341 PQueue 11

Insert Operation Must maintain CBT property (heap shape): Easy, just insert new element at the end of the array Min 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 ) 8/3/2007 UMBC CSMC 341 PQueue 12

Min BinaryHeap Insert (cont.) /** * Insert into the priority queue, maintaining heap order. * Duplicates are allowed. * @param x the item to insert. */ public void insert( AnyType x ) { if( currentsize == array.length - 1 ) enlargearray( array.length * 2 + 1 ); } // Percolate up int hole = ++currentsize; for( ; hole > 1&& x.compareto(array[hole/2]) < 0; hole/=2 ) array[ hole ] = array[ hole / 2 ]; array[ hole ] = x; 8/3/2007 UMBC CSMC 341 PQueue 13

Insert 14 8/3/2007 UMBC CSMC 341 PQueue 14

Deletion Operation Steps Remove min element (the root) Maintain heap shape Maintain min 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. 8/3/2007 UMBC CSMC 341 PQueue 15

Min BinaryHeap Deletion(cont.) /** * Remove the smallest item from the priority queue. * @return the smallest item, or throw UnderflowException, if empty. */ public AnyType deletemin( ) { if( isempty( ) ) throw new UnderflowException( ); AnyType minitem = findmin( ); array[ 1 ] = array[ currentsize-- ]; percolatedown( 1 ); } return minitem; 8/3/2007 UMBC CSMC 341 PQueue 16

MinBinaryHeap percolatedown(cont.) /** * Internal method to percolate down in the heap. * @param hole the index at which the percolate begins. */ private void percolatedown( int hole ) { int child; AnyType tmp = array[ hole ]; for( ; hole * 2 <= currentsize; hole = child ){ child = hole * 2; if( child!= currentsize && array[ child + 1 ].compareto( array[ child ] ) < 0 ) child++; if( array[ child ].compareto( tmp ) < 0 ) array[ hole ] = array[ child ]; else break; } array[ hole ] = tmp; } 8/3/2007 UMBC CSMC 341 PQueue 17

deletemin 8/3/2007 UMBC CSMC 341 PQueue 18

deletemin (cont.) 8/3/2007 UMBC CSMC 341 PQueue 19

Constructing a Min BinaryHeap 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 starting in the middle and working your way up towards the root for (int index = n/2 ; index > 0; index--) percolatedown( index ); 8/3/2007 UMBC CSMC 341 PQueue 20

Constructing a Min BinaryHeap(cont.) //Construct the binary heap given an array of items. public BinaryHeap( AnyType [ ] items ){ currentsize = items.length; array = (AnyType[]) new Comparable[ (currentsize + 2)*11/10 ]; int i = 1; for( AnyType item : items ) array[ i++ ] = item; buildheap( ); } // Establish heap order property from an arbitrary // arrangement of items. Runs in linear time. private void buildheap( ){ for( int i = currentsize / 2; i > 0; i-- ) percolatedown( i ); } 8/3/2007 UMBC CSMC 341 PQueue 21

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 + + 2 0 *h = h i= 0 i 2 ( h i) = 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 h i= 0 2 i h i= 0 i2 i 8/3/2007 UMBC CSMC 341 PQueue 22

Performance of Construction (cont.) But 2 h+1 -h-2 = O(2 h ) But n = 1 + 2 + 4 + + 2 h = Therefore, n = O(2 h ) So S = O(n) h i= 0 2 i A heap of n nodes can be built in O(n) time. 8/3/2007 UMBC CSMC 341 PQueue 23

Heap Sort Given n values we can sort them in place in O(n log n) time 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 (high down to low) order. With a max heap, it sorts in normal (low up to high) order. Given an unsorted array A[ ] of size n for (i = n-1; i >= 1; i--) { } x = findmin( ); deletemin( ); A[i+1] = x; 8/3/2007 UMBC CSMC 341 PQueue 24

Limitations MinBinary heaps support insert, findmin, deletemin, and construct efficiently. They do not efficiently support the meld or merge operation in which 2 BHs are merged into one. If H 1 and H 2 are of size n 1 and n 2, then the merge is in O(n 1 + n 2 ). 8/3/2007 UMBC CSMC 341 PQueue 25

Leftist Min Heap Supports findmin -- O( 1 ) deletemin -- O( lg n ) insert -- O( lg n ) construct -- O( n ) merge -- O( lg n ) 8/3/2007 UMBC CSMC 341 PQueue 26

Leftist Tree The null path length, npl(x), of a node, X, is defined as the length of the shortest path from X to a node without two children (a non-full node). Note that npl(null) = -1. A Leftist Tree 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. Proof : Suppose this was not true. Then, at some node the path on the left would be shorter than the path on the right, violating the leftist tree definition. 8/3/2007 UMBC CSMC 341 PQueue 27

Leftist Min Heap A leftist min heap is a leftist tree in which the values in the nodes obey heap order (the tree is partially ordered). Since a LMH is not necessarily a CBT we do not implement it in an array. An explicit tree implementation is used. Operations findmin deletemin insert construct -- return root value, same as MBH -- implemented using meld operation -- implemented using meld operation -- implemented using meld operation 8/3/2007 UMBC CSMC 341 PQueue 28

Merge // Merge rhs into the priority queue. // rhs becomes empty. rhs must be different from this. // @param rhs the other leftist heap. public void merge( LeftistHeap<AnyType> rhs ){ if( this == rhs ) return; // Avoid aliasing problems root = merge( root, rhs.root ); rhs.root = null; } // Internal method to merge two roots. // Deals with deviant cases and calls recursive merge1. private Node<AnyType> merge(node<anytype> h1, Node<AnyType> h2 ){ if( h1 == null ) return h2; if( h2 == null ) return h1; if( h1.element.compareto( h2.element ) < 0 ) return merge1( h1, h2 ); else return merge1( h2, h1 ); } 8/3/2007 UMBC CSMC 341 PQueue 29

Merge (cont.) /** * Internal method to merge two roots. * Assumes trees are not empty, and h1's root contains smallest item. */ private Node<AnyType> merge1( Node<AnyType> h1, Node<AnyType> h2 ) { if( h1.left == null ) // Single node h1.left = h2; // Other fields in h1 already accurate else { h1.right = merge( h1.right, h2 ); if( h1.left.npl < h1.right.npl ) swapchildren( h1 ); h1.npl = h1.right.npl + 1; } return h1; } 8/3/2007 UMBC CSMC 341 PQueue 30

Merge (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. 8/3/2007 UMBC CSMC 341 PQueue 31

8/3/2007 UMBC CSMC 341 PQueue 32

8/3/2007 UMBC CSMC 341 PQueue 33

8/3/2007 UMBC CSMC 341 PQueue 34

Student Exercise Show the steps needed to merge the Leftist Heaps below. The final result is shown on the next slide. 6 8 17 12 10 15 19 20 30 25 8/3/2007 UMBC CSMC 341 PQueue 35

Student Exercise Final Result 6 8 17 12 19 10 20 15 30 25 8/3/2007 UMBC CSMC 341 PQueue 36

Min Leftist Heap Operations Other operations implemented using Merge( ) insert (item) Make item into a 1-node LH, X Merge(this, X) deletemin Merge(left subtree, right subtree) construct from N items Make N LHs from the N values, one element in each Merge each in one at a time (simple, but slow) use queue and build pairwise (complex but faster) 8/3/2007 UMBC CSMC 341 PQueue 37

LH Construct Algorithm: Make n leftist heaps, H 1.H n each with one data value Instantiate Queue<LeftistHeap> q; for (i = 1; i <= n; i++) q.enqueue(h i ); Leftist Heap h = q.dequeue( ); while (!q.isempty( ) ) q.enqueue( merge( h, q.dequeue( ) ) ); h = q.dequeue( ); 8/3/2007 UMBC CSMC 341 PQueue 38