Heaps and Priority Queues

Similar documents
Priority queues implemented via heaps

Binary Search Trees. Motivation

CS Data Structures and Algorithm Analysis

ENS Lyon Camp. Day 2. Basic group. Cartesian Tree. 26 October

Chapter 5 Data Structures Algorithm Theory WS 2017/18 Fabian Kuhn

Insertion Sort. We take the first element: 34 is sorted

COMP 250. Lecture 24. heaps 2. Nov. 3, 2017

Objec&ves. Review. Data structure: Heaps Data structure: Graphs. What is a priority queue? What is a heap?

8 Priority Queues. 8 Priority Queues. Prim s Minimum Spanning Tree Algorithm. Dijkstra s Shortest Path Algorithm

Review Of Topics. Review: Induction

2-INF-237 Vybrané partie z dátových štruktúr 2-INF-237 Selected Topics in Data Structures

INF2220: algorithms and data structures Series 1

Lecture 14: Nov. 11 & 13

Divide-and-Conquer Algorithms Part Two

Fibonacci Heaps These lecture slides are adapted from CLRS, Chapter 20.

Tree Heap Priority Queue

CSE548, AMS542: Analysis of Algorithms, Fall 2017 Date: Oct 26. Homework #2. ( Due: Nov 8 )

CS213d Data Structures and Algorithms

Fibonacci (Min-)Heap. (I draw dashed lines in place of of circular lists.) 1 / 17

Binary Search Trees. Lecture 29 Section Robb T. Koether. Hampden-Sydney College. Fri, Apr 8, 2016

Part IA Algorithms Notes

Advanced Implementations of Tables: Balanced Search Trees and Hashing

Mon Tue Wed Thurs Fri

Solution suggestions for examination of Logic, Algorithms and Data Structures,

Assignment 5: Solutions

Quiz 1 Solutions. Problem 2. Asymptotics & Recurrences [20 points] (3 parts)

Algorithm runtime analysis and computational tractability

University of New Mexico Department of Computer Science. Midterm Examination. CS 361 Data Structures and Algorithms Spring, 2003

Algorithms Theory. 08 Fibonacci Heaps

Data Structures and Algorithms

Amortized analysis. Amortized analysis

Dijkstra s Single Source Shortest Path Algorithm. Andreas Klappenecker

Slides for CIS 675. Huffman Encoding, 1. Huffman Encoding, 2. Huffman Encoding, 3. Encoding 1. DPV Chapter 5, Part 2. Encoding 2

Dictionary: an abstract data type

Fundamental Algorithms

Algorithms. Algorithms 2.4 PRIORITY QUEUES. Pro tip: Sit somewhere where you can work in a group of 2 or 3

Dictionary: an abstract data type

Algorithm Design and Analysis

Greedy Algorithms. CSE 101: Design and Analysis of Algorithms Lecture 10

CPSC 320 Sample Final Examination December 2013

! Insert. ! Remove largest. ! Copy. ! Create. ! Destroy. ! Test if empty. ! Fraud detection: isolate $$ transactions.

Randomized Sorting Algorithms Quick sort can be converted to a randomized algorithm by picking the pivot element randomly. In this case we can show th

Analysis of Algorithms. Outline 1 Introduction Basic Definitions Ordered Trees. Fibonacci Heaps. Andres Mendez-Vazquez. October 29, Notes.

CS 151. Red Black Trees & Structural Induction. Thursday, November 1, 12

The Greedy Method. Design and analysis of algorithms Cs The Greedy Method

25. Minimum Spanning Trees

25. Minimum Spanning Trees

Tutorial 4. Dynamic Set: Amortized Analysis

Data Structures and Algorithms " Search Trees!!

Each internal node v with d(v) children stores d 1 keys. k i 1 < key in i-th sub-tree k i, where we use k 0 = and k d =.

Data Structures 1 NTIN066

Weak Heaps and Friends: Recent Developments

FIBONACCI HEAPS. preliminaries insert extract the minimum decrease key bounding the rank meld and delete. Copyright 2013 Kevin Wayne

Amortized Analysis. DistributeMoney(n, k) 1 Each of n people gets $1. 2 for i = 1to k 3 do Give a dollar to a random person

1. Introduction Bottom-Up-Heapsort is a variant of the classical Heapsort algorithm due to Williams ([Wi64]) and Floyd ([F64]) and was rst presented i

Greedy Alg: Huffman abhi shelat

CS 240 Data Structures and Data Management. Module 4: Dictionaries

Premaster Course Algorithms 1 Chapter 3: Elementary Data Structures

Data Structures 1 NTIN066

16. Binary Search Trees. [Ottman/Widmayer, Kap. 5.1, Cormen et al, Kap ]

Chapter 5 Arrays and Strings 5.1 Arrays as abstract data types 5.2 Contiguous representations of arrays 5.3 Sparse arrays 5.4 Representations of

16. Binary Search Trees. [Ottman/Widmayer, Kap. 5.1, Cormen et al, Kap ]

CS361 Homework #3 Solutions

Heaps Induction. Heaps. Heaps. Tirgul 6

4.8 Huffman Codes. These lecture slides are supplied by Mathijs de Weerd

1 ListElement l e = f i r s t ; / / s t a r t i n g p o i n t 2 while ( l e. next!= n u l l ) 3 { l e = l e. next ; / / next step 4 } Removal

Shortest Path Algorithms

Algorithms and Data Structures 2016 Week 5 solutions (Tues 9th - Fri 12th February)

/463 Algorithms - Fall 2013 Solution to Assignment 4

Outline. Computer Science 331. Cost of Binary Search Tree Operations. Bounds on Height: Worst- and Average-Case

Lecture 1 : Data Compression and Entropy

Search Trees. Chapter 10. CSE 2011 Prof. J. Elder Last Updated: :52 AM

Problem 5. Use mathematical induction to show that when n is an exact power of two, the solution of the recurrence

Data Structures and and Algorithm Xiaoqing Zheng

CSE 4502/5717 Big Data Analytics Spring 2018; Homework 1 Solutions

Functional Data Structures

Search Trees. EECS 2011 Prof. J. Elder Last Updated: 24 March 2015

Analysis of Algorithms - Midterm (Solutions)

Lecture 6 September 21, 2016

AVL trees. AVL trees

Sorting. Chapter 11. CSE 2011 Prof. J. Elder Last Updated: :11 AM

CSE 202: Design and Analysis of Algorithms Lecture 3

Chapter 4. Greedy Algorithms. Slides by Kevin Wayne. Copyright 2005 Pearson-Addison Wesley. All rights reserved.

Week 5: Quicksort, Lower bound, Greedy

Data selection. Lower complexity bound for sorting

HW #4. (mostly by) Salim Sarımurat. 1) Insert 6 2) Insert 8 3) Insert 30. 4) Insert S a.

Tutorial Session 5. Discussion of Exercise 4, Preview on Exercise 5, Preparation for Midterm 1. Running Time Analysis, Asymptotic Complexity

1 Trees. Listing 1: Node with two child reference. public class ptwochildnode { protected Object data ; protected ptwochildnode l e f t, r i g h t ;

Greedy. Outline CS141. Stefano Lonardi, UCR 1. Activity selection Fractional knapsack Huffman encoding Later:

The null-pointers in a binary search tree are replaced by pointers to special null-vertices, that do not carry any object-data

AVL Trees. Manolis Koubarakis. Data Structures and Programming Techniques

Greedy Algorithms and Data Compression. Curs 2018

Elementary Sorts 1 / 18

CS60007 Algorithm Design and Analysis 2018 Assignment 1

CMSC 132, Object-Oriented Programming II Summer Lecture 12

CS 580: Algorithm Design and Analysis

Outline Resource Introduction Usage Testing Exercises. Linked Lists COMP SCI / SFWR ENG 2S03. Department of Computing and Software McMaster University

3 Greedy Algorithms. 3.1 An activity-selection problem

Another way of saying this is that amortized analysis guarantees the average case performance of each operation in the worst case.

Problem. Problem Given a dictionary and a word. Which page (if any) contains the given word? 3 / 26

Transcription:

Heaps and Priority Queues Motivation Situations where one has to choose the next most important from a collection. Examples: patients in an emergency room, scheduling programs in a multi-tasking OS. Need to choose the task with the highest priority A priority queue orders elements by their importance. A queue is insufficient, need an efficient solution. A binary search tree is also insufficient, especially worst case. Data Structures 1 Heaps and Priority Queues

Complete Binary Trees(Review) Tree of d levels, in which all levels are filled, except possibly d 1. Bottom most level has nodes filled in from the left. A B C E F H I J K L Data Structures 2 Heaps and Priority Queues

Why a Complete Binary Tree for a Heap No Pointers! Can use an array representation for the tree. Number node positions in level order. Nodes are positioned in an array in level order. Node Determination: Parent(r) = (r 1)/2, if 0 < r < n Left child(r) = 2r + 1 if 2r + 1 < n Right child(r) = 2r + 2 if 2r + 2 < n Left sibling(r) = r 1 if r is even and 0 < r < n Right sibling(r) = r + 1 if r is odd and r + 1 < n Data Structures 3 Heaps and Priority Queues

Heap Data Type Complete binary tree with the Heap Property. Heap has partial ordering. Min-heap: All nodes have values less than child values. Max-heap: All nodes have values greater than child values. The root stores the smallest value in a min-heap, largest value in a max-heap No relationship between node and its sibling in heaps. Applications: Heapsort uses the max-heap, replacement selection algorithm using the min-heap. Data Structures 4 Heaps and Priority Queues

Heap Data Type 28 7 20 6 20 14 17 11 3 5 28 22 16 35 3 8 29 33 MAX Heap MIN Heap Data Structures 5 Heaps and Priority Queues

Heap Operations Build the heap May insert one element at a time If all elements are available, can re-heap Insert Remove Data Structures 6 Heaps and Priority Queues

Heap Ops:Build Heap Use principle of induction: make subtrees to be heaps prior to tackling their root. Root may sift down. Work from the middle of the array (high end to low end). 1 7 2 3 5 6 4 5 6 7 4 2 1 3 Exchanges: (5 2), (7 3), (7 1), (6 1) Data Structures 7 Heaps and Priority Queues

Heap Ops:Insert Insert element to last position of the array. Reheap using exchanges (move up towards root). 28 Insert 30 28 20 6 20 6 17 11 3 5 17 11 3 5 3 8 3 8 30 Data Structures 8 Heaps and Priority Queues

Heap Ops:Remove (Max) Root element removed. Bring last element to the root. Reheap 28 Delete 28 8 20 6 20 6 17 11 3 5 17 11 3 5 3 8 3 Data Structures 9 Heaps and Priority Queues

Heap Ops:Remove (at position p) Exchange element to be deleted with last element. Compare p to its parent and move up as needed, until the root is reached. Sift down from position p. Data Structures 10 Heaps and Priority Queues

Max Heap Implementation public class MaxHeap<E extends Comparable<? super E>> { private E [ ] Heap ; / / P o i n t e r to the heap array private i n t size ; / / Maximum size of the heap private i n t n ; / / Number of t h i n g s i n heap public MaxHeap(E [ ] h, i n t num, i n t max) { Heap = h ; n = num ; size = max ; buildheap ( ) ; / / Return c u r r e n t size of the heap public i n t heapsize ( ) { return n ; / / I s pos a l e a f p o s i t i o n? public boolean i s L e a f ( i n t pos ) { return ( pos >= n / 2 ) && ( pos < n ) ; Data Structures 11 Heaps and Priority Queues

Max Heap Implementation:Access Functions / / Return p o s i t i o n f o r l e f t c h i l d of pos public i n t l e f t c h i l d ( i n t pos ) { a s s e r t pos < n /2 : P o s i t i o n has no l e f t c h i l d ; return 2 pos + 1; / / Return p o s i t i o n f o r r i g h t c h i l d of pos public i n t r i g h t c h i l d ( i n t pos ) { a s s e r t pos < ( n 1)/2 : P o s i t i o n has no r i g h t c h i l d ; return 2 pos + 2; / / Return p o s i t i o n f o r parent public i n t parent ( i n t pos ) { a s s e r t pos > 0 : P o s i t i o n has no parent ; return ( pos 1)/2; / / Heapify contents of Heap / public void buildheap ( ) { for ( i n t i =n/2 1; i >=0; i ) s i f t d o w n ( i ) ; Data Structures 12 Heaps and Priority Queues

Max Heap Implementation:Insert / / I n s e r t i n t o heap public void i n s e r t (E v a l ) { a s s e r t n < size : Heap i s f u l l ; i n t c u r r = n++; Heap [ c u r r ] = v a l ; / / S t a r t at end of heap / / Now s i f t up u n t i l c u r r s parent s key > c u r r s key while ( ( c u r r!= 0) && ( Heap [ c u r r ]. compareto ( Heap [ parent ( c u r r ) ] ) > 0 ) ) { D S u t i l. swap ( Heap, curr, parent ( c u r r ) ) ; c u r r = parent ( c u r r ) ; Data Structures 13 Heaps and Priority Queues

Max Heap Implementation:siftdown / / Put element i n i t s c o r r e c t place / private void s i f t d o w n ( i n t pos ) { a s s e r t ( pos >= 0) && ( pos < n ) : I l l e g a l heap p o s i t i o n ; while (! i s L e a f ( pos ) ) { i n t j = l e f t c h i l d ( pos ) ; i f ( ( j <(n 1)) && ( Heap [ j ]. compareto ( Heap [ j + 1 ] ) < 0 ) ) j ++; / / j i s now index of c h i l d with g r e a t e r value i f ( Heap [ pos ]. compareto ( Heap [ j ] ) >= 0) return ; D S u t i l. swap ( Heap, pos, j ) ; pos = j ; / / Move down Data Structures 14 Heaps and Priority Queues

Max Heap Implementation:remove public E removemax ( ) { / / Remove maximum value a s s e r t n > 0 : Removing from empty heap ; D S u t i l. swap ( Heap, 0, n ) ; / / Swap maximum with l a s t va i f ( n!= 0) / / Not on l a s t element s i f t d o w n ( 0 ) ; / / Put new heap r o o t v a l i n c o r r e c t pl return Heap [ n ] ; / / Remove element at s p e c i f i e d p o s i t i o n public E remove ( i n t pos ) { a s s e r t ( pos >= 0) && ( pos < n ) : I l l e g a l heap p o s i t i o n D S u t i l. swap ( Heap, pos, n ) ; / / Swap with l a s t value / / I f we j u s t swapped i n a big value, push i t up while ( Heap [ pos ]. compareto ( Heap [ parent ( pos ) ] ) > 0) { D S u t i l. swap ( Heap, pos, parent ( pos ) ) ; pos = parent ( pos ) ; i f ( n!= 0) s i f t d o w n ( pos ) ; / / I f i t i s l i t t l e, push down return Heap [ n ] ; Data Structures 15 Heaps and Priority Queues

Cost of Heap Construction Level n 1 of the heap has half the number of nodes at level n. Nodes move down from each level of the tree; node at level i: (i 1) moves. log n (i 1) n 2 Θ(n) i i=1 Data Structures 16 Heaps and Priority Queues