CH 8. HEAPS AND PRIORITY QUEUES

Similar documents
CH. 8 PRIORITY QUEUES AND HEAPS

Stores a collection of elements each with an associated key value

Heaps 2. Recall Priority Queue ADT. Heaps 3/19/14

Heaps Goodrich, Tamassia. Heaps 1

Heaps. 2/13/2006 Heaps 1

HEAPS: IMPLEMENTING EFFICIENT PRIORITY QUEUES

Priority Queues and Heaps. Heaps and Priority Queues 1

Heaps and Priority Queues

Priority Queues. Outline. COMP9024: Data Structures and Algorithms. Priority Queue ADT. Total Order Relations. Entry ADT

Priority Queue ADT ( 7.1) Heaps and Priority Queues 2. Comparator ADT ( 7.1.4) Total Order Relation. Using Comparators in C++

Data Structures and Algorithms " Priority Queues!

Priority Queues & Heaps. Chapter 9

Sorting. Outline. Sorting with a priority queue Selection-sort Insertion-sort Heap Sort Quick Sort

CSED233: Data Structures (2017F) Lecture9: Priority Queues and Heaps

Describe how to implement deque ADT using two stacks as the only instance variables. What are the running times of the methods

Data Structures Lecture 7

Chapter 2: Basic Data Structures

Priority Queues. Reading: 7.1, 7.2

Elementary Data Structures 2

Algorithms and Data Structures

Priority Queues and Heaps. More Data Structures. Priority Queue ADT ( 2.4.1) Total Order Relation. Sorting with a Priority Queue ( 2.4.

Data Structures and Algorithms

Programming II (CS300)

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

Priority Queues & Heaps. CS16: Introduction to Data Structures & Algorithms Spring 2019

Priority Queues 3/19/14

1/27/2005 2:03 AM Priority Queues 1. Outline and Reading

Programming II (CS300)

Sorting and Searching

DataStruct 8. Heaps and Priority Queues

Sorting and Searching

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

Priority Queues Goodrich, Tamassia. Priority Queues 1

Data Structures and Algorithms for Engineers

CS 240 Fall Mike Lam, Professor. Priority Queues and Heaps

Priority queues. Priority queues. Priority queue operations

Priority Queues Heaps Heapsort

csci 210: Data Structures Priority Queues and Heaps

Definition of a Heap. Heaps. Priority Queues. Example. Implementation using a heap. Heap ADT

Height of a Heap. Heaps. 1. Insertion into a Heap. Heaps and Priority Queues. The insertion algorithm consists of three steps

Heaps and Priority Queues

CS165: Priority Queues, Heaps

Binary Trees, Binary Search Trees

Data Structures and Algorithms

Priority Queues and Binary Heaps

(2,4) Trees Goodrich, Tamassia (2,4) Trees 1

Algorithms and Theory of Computation. Lecture 7: Priority Queue

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard

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

Adding a Node to (Min) Heap. Lecture16: Heap Sort. Priority Queue Sort. Delete a Node from (Min) Heap. Step 1: Add node at the end

In a postorder traversal, a node is visited after its descendants Application: compute space used by files in a directory and its subdirectories 9 1

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

Winter 2016 COMP-250: Introduction to Computer Science. Lecture 20, March 24, 2016

CSCI2100B Data Structures Heaps

Trees & Tree-Based Data Structures. Part 4: Heaps. Definition. Example. Properties. Example Min-Heap. Definition

Binary Trees

Priority Queues. INFO0902 Data Structures and Algorithms. Priority Queues (files à priorités) Keys. Priority Queues

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

Chapter 20: Binary Trees

Priority queues. Priority queues. Priority queue operations

Binary Search Trees Treesort

9. Heap : Priority Queue

Chapter 10: Search Trees

CHAPTER 10 AVL TREES. 3 8 z 4

Priority Queues Heaps Heapsort

CSE100. Advanced Data Structures. Lecture 13. (Based on Paul Kube course materials)

Binary Heaps in Dynamic Arrays

Heaps. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015

Round 3: Trees. Tommi Junttila. Aalto University School of Science Department of Computer Science. CS-A1140 Data Structures and Algorithms Autumn 2017

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

Lecture 11: Multiway and (2,4) Trees. Courtesy to Goodrich, Tamassia and Olga Veksler

(2,4) Trees. 2/22/2006 (2,4) Trees 1

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

Entry and Priority Queue ADTs

COMP250: Priority queue ADT, Heaps. Lecture 23 Jérôme Waldispühl School of Computer Science McGill University

Partha Sarathi Manal

Course Review. Cpt S 223 Fall 2009

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

Heapsort. Heap data structure

Binary search trees. Binary search trees are data structures based on binary trees that support operations on dynamic sets.

Binary heaps (chapters ) Leftist heaps

Binary search trees 3. Binary search trees. Binary search trees 2. Reading: Cormen et al, Sections 12.1 to 12.3

Binary Trees. Directed, Rooted Tree. Terminology. Trees. Binary Trees. Possible Implementation 4/18/2013

BM267 - Introduction to Data Structures

DATA STRUCTURES AND ALGORITHMS

OUTLINE. General Trees (Ch. 7.1) Binary Trees (Ch. 7.3) Tree Traversals (Ch. 7.2)

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

Chapter 6 Heaps. Introduction. Heap Model. Heap Implementation

INFO1x05 Tutorial 6. Exercise 1: Heaps and Priority Queues

Binary Search Trees > = 2014 Goodrich, Tamassia, Goldwasser. Binary Search Trees 1

Topic: Heaps and priority queues

Algorithms and Data Structures

Priority queue ADT Heaps. Lecture 21

Properties of a heap (represented by an array A)

CSE 241 Class 17. Jeremy Buhler. October 28, Ordered collections supported both, plus total ordering operations (pred and succ)

CS106X Programming Abstractions in C++ Dr. Cynthia Bailey Lee

Programming II (CS300)

Module 2: Priority Queues

DIVIDE AND CONQUER ALGORITHMS ANALYSIS WITH RECURRENCE EQUATIONS

Topics on the Midterm

Transcription:

CH 8. HEAPS AND PRIORITY QUEUES ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND MOUNT (WILEY 2004) AND SLIDES FROM NANCY M. AMATO

OUTLINE AND READING PriorityQueue ADT (Ch. 8.1) Total order relation (Ch. 8.1.1) Comparator ADT (Ch. 8.1.2) Sorting with a Priority Queue (Ch. 8.1.) Implementing a PQ with a list (Ch. 8.2) Selection-sort and Insertion Sort (Ch. 8.2.2) Heaps (Ch. 8.3) Complete Binary Trees (Ch. 8.3.2) Implementing a PQ with a heap (Ch. 8.3.3) Heapsort (Ch. 8.3.)

PRIORITY QUEUES Stores a collection of elements each with an associated key value Can insert as many elements in any order Only can inspect and remove a single element the minimum (or maximum depending) element Applications Standby Flyers Auctions Stock market

TOTAL ORDER RELATION Keys in a priority queue can be arbitrary objects on which an order is defined, e.g., integers Two distinct items in a priority queue can have the same key Mathematical concept of total order relation Reflexive property: k k Antisymmetric property: if k 1 k 2 and k 2 k 1, then k 1 = k 2 Transitive property: if k 1 k 2 and k 2 k 3 then k 1 k 3

COMPARATOR ADT A comparator encapsulates the action of comparing two objects according to a given total order relation A generic priority queue uses a comparator as a template argument, to define the comparison function ( ) The comparator is external to the keys being compared. Thus, the same objects can be sorted in different ways by using different comparators. When the priority queue needs to compare two keys, it uses its comparator

PRIORITY QUEUE ADT A priority queue stores a collection of items each with an associated key value Main methods insert(e) inserts an element e removemin() removes the item with the smallest key min() return an element with the smallest key size(), empty()

PRIORITYQUEUESORT() SORTING WITH A PRIORITY QUEUE We can use a priority queue to sort a set of comparable elements Insert the elements one by one with a series of insert(e) operations Remove the elements in sorted order with a series of removemin() operations Running time depends on the PQ implementation Algorithm PriorityQueueSort() Input: List L storing n elements and a Comparator C Output: Sorted List L 1. Priority Queue P using comparator C 2. while L. empty() do 3. P. insert(l. front()) 4. L. erasefront(). while P. empty() do. L. insertback(p. min()) 7. P. removemin() 8. return L

LIST-BASED PRIORITY QUEUE Unsorted list implementation Store the items of the priority queue in a list, in arbitrary order Sorted list implementation Store the items of the priority queue in a list, sorted by key 4 2 3 1 1 2 3 4 Performance: insert(e) takes O(1) time since we can insert the item at the beginning or end of the list removemin() and min() take O(n) time since we have to traverse the entire sequence to find the smallest key Performance: insert(e) takes O(n) time since we have to find the place where to insert the item removemin() and min() take O(1) time since the smallest key is at the beginning of the list

SELECTION-SORT Selection-sort is the variation of PQ-sort where the priority queue is implemented with an unsorted list Running time of Selection-sort: Inserting the elements into the priority queue with n insert(e) operations takes O(n) time Removing the elements in sorted order from the priority queue with n removemin() operations takes time proportional to n i=0 Selection-sort runs in O n 2 4 2 3 1 n i = n + n 1 + + 2 + 1 = O n 2 time

EXERCISE SELECTION-SORT Selection-sort is the variation of PQ-sort where the priority queue is implemented with an unsorted list (do n insert e and then n removemin()) 4 2 3 1 Illustrate the performance of selection-sort on the following input sequence: (22, 1, 3, 44, 10, 3, 9, 13, 29, 2)

INSERTION-SORT Insertion-sort is the variation of PQ-sort where the priority queue is implemented with a sorted List Running time of Insertion-sort: Inserting the elements into the priority queue with n insert e operations takes time proportional to n i=0 i = 1 + 2 + + n = O n 2 Removing the elements in sorted order from the priority queue with a series of n removemin() operations takes O n time Insertion-sort runs in O n 2 time 1 2 3 4

EXERCISE INSERTION-SORT Insertion-sort is the variation of PQ-sort where the priority queue is implemented with a sorted list (do n insert e and then n removemin()) 1 2 3 4 Illustrate the performance of insertion-sort on the following input sequence: (22, 1, 3, 44, 10, 3, 9, 13, 29, 2)

IN-PLACE INSERTION-SORT Instead of using an external data structure, we can implement selectionsort and insertion-sort in-place (only O(1) extra storage) A portion of the input list itself serves as the priority queue For in-place insertion-sort We keep sorted the initial portion of the list We can use swap(i, j) instead of modifying the list 4 2 3 1 4 2 3 1 4 2 3 1 2 4 3 1 2 3 4 1 1 2 3 4 1 2 3 4

2 HEAPS 9 7

WHAT IS A HEAP? A heap is a binary tree storing keys at its internal nodes and satisfying the following properties: Heap-Order: for every node v other than the root, key v key(v. parent()) Complete Binary Tree: let h be the height of the heap for i = 0 h 1, there are 2 i nodes on level i at level h, nodes are filled from left to right Can be used to store a priority queue efficiently 9 7 2 last node

HEIGHT OF A HEAP Theorem: A heap storing n keys has height O log n Proof: (we apply the complete binary tree property) Let h be the height of a heap storing h keys Since there are 2 i keys at level i = 0 h 1 and at least one key on level h, we have n 1 + 2 + 4 + + 2 h 1 + 1 = 2 h 1 + 1 = 2 h Level h has at most 2 h nodes: n 2 h+1 1 Thus, log n + 1 1 h log n depth 0 1 h 1 h keys 1 2 2 h 1 1

EXERCISE HEAPS Let H be a heap with 7 distinct elements (1,2,3,4,,, and 7). Is it possible that a preorder traversal visits the elements in sorted order? What about an inorder traversal or a postorder traversal? In each case, either show such a heap or prove that none exists.

INSERTION INTO A HEAP 2 insert(e) consists of three steps Find the insertion node z (the new last node) Store e at z and expand z into an internal node Restore the heap-order property (discussed next) 9 7 2 9 7 1 z insertion node z

UPHEAP After the insertion of a new element e, the heap-order property may be violated Up-heap bubbling restores the heap-order property by swapping e along an upward path from the insertion node Upheap terminates when e reaches the root or a node whose parent has a key smaller than or equal to key(e) Since a heap has height O(log n), upheap runs in O log n time 2 1 9 7 z 1 z 9 7 2

REMOVAL FROM A HEAP 2 removemin() corresponds to the removal of the root from the heap The removal algorithm consists of three steps Replace the root with the element of the last node w Compress w and its children into a leaf Restore the heap-order property (discussed next) 9 9 w 7 w 7 last node

DOWNHEAP After replacing the root element of the last node, the heap-order property may be violated Down-heap bubbling restores the heap-order property by swapping element e along a downward path from the root Downheap terminates when e reaches a leaf or a node whose children have keys greater than or equal to key(e) Since a heap has height O log n, downheap runs in O(log n) time 7 9 w 9 7 w

UPDATING THE LAST NODE The insertion node can be found by traversing a path of O(log n) nodes Go up until a left child or the root is reached If a left child is reached, go to the right child Go down left until a leaf is reached Similar algorithm for updating the last node after a removal

HEAP-SORT Consider a priority queue with n items implemented by means of a heap the space used is O(n) insert(e) and removemin() take O log n time min(), size(), and empty() take O 1 time Using a heap-based priority queue, we can sort a sequence of n elements in O(n log n) time The resulting algorithm is called heap-sort Heap-sort is much faster than quadratic sorting algorithms, such as insertion-sort and selection-sort

EXERCISE HEAP-SORT Heap-sort is the variation of PQ-sort where the priority queue is implemented with a heap (do n insert e and then n removemin()) Illustrate the performance of heap-sort on the following input sequence (draw the heap at each step): (22, 1, 3, 44, 10, 3, 9, 13, 29, 2)

VECTOR-BASED HEAP IMPLEMENTATION We can represent a heap with n elements by means of a vector of length n + 1 Links between nodes are not explicitly stored The leaves are not represented The cell at index 0 is not used For the node at index i the left child is at index 2i the right child is at index 2i + 1 insert(e) corresponds to inserting at index n + 1 removemin() corresponds to removing element at index n Yields in-place heap-sort 9 0 2 7 2 9 7 1 2 3 4

PRIORITY QUEUE SUMMARY insert(e) removemin() PQ-Sort total Ordered List (Insertion Sort) O(n) O(1) O(n 2 ) Unordered List (Selection Sort) Binary Heap, Vector-based Heap (Heap Sort) O(1) O(n) O(n 2 ) O log n O log n O n log n

MERGING TWO HEAPS 3 2 8 4 We are given two two heaps and a new element e 7 We create a new heap with a root node storing e and with the two 8 3 4 2 heaps as subtrees We perform downheap to restore the heap-order property 3 2 4 8 7

BOTTOM-UP HEAP CONSTRUCTION We can construct a heap storing n given elements in using a bottom-up construction with log n phases In phase i, pairs of heaps with 2 i 1 elements are merged into heaps with 2 i+1 1 elements 2 i -1 2 i -1 2 i+1-1

EXAMPLE 1 1 4 12 7 23 20 2 11 27 1 1 4 12 7 23 20

EXAMPLE 2 11 27 1 1 4 12 9 23 20 1 4 23 1 2 12 11 9 27 20

EXAMPLE 7 8 1 4 23 1 2 12 11 9 27 20 4 1 8 23 1 2 7 12 11 9 27 20

EXAMPLE 10 4 1 8 23 1 2 7 12 11 9 27 20 4 1 7 8 23 1 2 10 12 11 9 27 20

ANALYSIS We visualize the worst-case time of a downheap with a proxy path that goes first right and then repeatedly goes left until the bottom of the heap (this path may differ from the actual downheap path) Since each node is traversed by at most two proxy paths, the total number of nodes of the proxy paths is O(n) Thus, bottom-up heap construction runs in O(n) time Bottom-up heap construction is faster than n successive insertions and speeds up the first phase of heap-sort

ADAPTABLE PRIORITY QUEUES One weakness of the priority queues so far is that we do not have an ability to update individual entries, like in a changing price market or bidding service We incorporate concept of positions to accomplish this (similar to List) Additional ADT support (also includes standard priority queue functionality) insert(e) insert element e into priority queue and return a position referring to this entry remove(p) remove the entry referenced by position p replace(p, e) replace with e the element associated with position p and return the position of the altered entry

LOCATION-AWARE ENTRY Locators decouple positions and entries in order to support efficient adaptable priority queue implementations (i.e., in a heap) a Each position has an associated locator Each locator stores a pointer to its position and memory for the entry g e

POSITIONS VS. LOCATORS Position represents a place in a data structure related to other positions in the data structure (e.g., previous/next or parent/child) often implemented as a pointer to a node or the index of an array cell Position-based ADTs (e.g., sequence and tree) are fundamental data storage schemes Locator identifies and tracks a (key, element) item unrelated to other locators in the data structure often implemented as an object storing the item and its position in the underlying structure Key-based ADTs (e.g., priority queue) can be augmented with locator-based methods