Priority Queues. Problem. Let S={(s1,p1), (s2,p2),,(sn,pn)} where s(i) is a key and p(i) is the priority of s(i).

Similar documents
Data Structures and Algorithms

CS350: Data Structures Heaps and Priority Queues

Priority Queues and Binary Heaps

Priority queues. Priority queues. Priority queue operations

Sorting and Searching

Sorting and Searching

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

CH 8. HEAPS AND PRIORITY QUEUES

BM267 - Introduction to Data Structures

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

CH. 8 PRIORITY QUEUES AND HEAPS

csci 210: Data Structures Priority Queues and Heaps

HEAPS: IMPLEMENTING EFFICIENT PRIORITY QUEUES

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

Heaps and Priority Queues

CSCI2100B Data Structures Heaps

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

Priority queue ADT Heaps. Lecture 21

Heaps Goodrich, Tamassia. Heaps 1

Chapter 6 Heaps. Introduction. Heap Model. Heap Implementation

9. Heap : Priority Queue

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

Priority Queues. Priority Queues Trees and Heaps Representations of Heaps Algorithms on Heaps Building a Heap Heapsort.

Programming II (CS300)

Heaps. 2/13/2006 Heaps 1

Heapsort. Heap data structure

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

1 Tree Sort LECTURE 4. OHSU/OGI (Winter 2009) ANALYSIS AND DESIGN OF ALGORITHMS

Stores a collection of elements each with an associated key value

Collection of priority-job pairs; priorities are comparable.

Priority Queues (Heaps)

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

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

Data Structures and Algorithms for Engineers

Chapter 6 Heapsort 1

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

HEAP. Michael Tsai 2017/4/25

Recall: Properties of B-Trees

403: Algorithms and Data Structures. Heaps. Fall 2016 UAlbany Computer Science. Some slides borrowed by David Luebke

Computer Science 210 Data Structures Siena College Fall Topic Notes: Priority Queues and Heaps

Binary Heaps in Dynamic Arrays

Introduction to Algorithms 3 rd edition

Data Structures Lesson 9

Priority Queues and Heaps. Heaps and Priority Queues 1

The Heap Data Structure

Figure 1: A complete binary tree.

Topic: Heaps and priority queues

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

Design and Analysis of Algorithms

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

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

Programming II (CS300)

Algorithms and Data Structures

Heaps. Heaps Priority Queue Revisit HeapSort

Algorithms and Data Structures

CS165: Priority Queues, Heaps

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?

Priority Queues Heaps Heapsort

Priority Queues Heaps Heapsort

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

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

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

Algorithms, Spring 2014, CSE, OSU Lecture 2: Sorting

Binary Trees

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

Figure 1: A complete binary tree.

Binary Heaps. CSE 373 Data Structures Lecture 11

Dictionaries. Priority Queues

CS60020: Foundations of Algorithm Design and Machine Learning. Sourangshu Bhattacharya

quiz heapsort intuition overview Is an algorithm with a worst-case time complexity in O(n) data structures and algorithms lecture 3

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

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

Algorithms and Theory of Computation. Lecture 7: Priority Queue

Module 2: Priority Queues

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

CS 240 Data Structures and Data Management. Module 2: Priority Queues

Data Structures and Algorithms. Roberto Sebastiani

CS 240 Data Structures and Data Management. Module 2: Priority Queues

Properties of a heap (represented by an array A)

Heap: A binary heap is a complete binary tree in which each, node other than root is smaller than its parent. Heap example: Fig 1. NPTEL IIT Guwahati

Heaps, Heap Sort, and Priority Queues.

Priority queues. Priority queues. Priority queue operations

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

Administration CSE 326: Data Structures

Lecture 5 Using Data Structures to Improve Dijkstra s Algorithm. (AM&O Sections and Appendix A)

Trees. A tree is a directed graph with the property

CS711008Z Algorithm Design and Analysis

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

CS711008Z Algorithm Design and Analysis

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

Heaps. Heapsort. [Reading: CLRS 6] Laura Toma, csci2000, Bowdoin College

CSC Design and Analysis of Algorithms. Lecture 8. Transform and Conquer II Algorithm Design Technique. Transform and Conquer

CMSC 341 Lecture 14: Priority Queues, Heaps

CSC Design and Analysis of Algorithms. Lecture 8. Transform and Conquer II Algorithm Design Technique. Transform and Conquer

BINARY HEAP cs2420 Introduction to Algorithms and Data Structures Spring 2015

Section 4 SOLUTION: AVL Trees & B-Trees

Binary Heaps. COL 106 Shweta Agrawal and Amit Kumar

CMSC 341 Lecture 15 Leftist Heaps

Data Structures and Algorithms

Appendix A and B are also worth reading.

Transcription:

Priority Queues

Priority Queues Problem. Let S={(s1,p1), (s2,p2),,(sn,pn)} where s(i) is a key and p(i) is the priority of s(i). How to design a data structure/algorithm to support the following operations over S? ExtractMin: Returns the element of S with minimum priority Insert(s,p): Insert a new element (s,p) in S RemoveMin: Remove the element in S with minimum p

Priority Queues Solution 1. Used a sorted list ExtractMin : O(1) time Insert: O(n) time DeleteMin: O(1) time Solution 2. Use a list with the pair with minimum p at the first position ExtractMin : O(1) time Insert: O(1) time DeleteMin: O(n) time Can we do better? How?

Priority Queues Solution 1. Used a sorted list ExtractMin : O(1) time Insert: O(n) time DeleteMin: O(1) time Solution 2. Use a list with the pair with minimum p at the first position ExtractMin : O(1) time Insert: O(1) time DeleteMin: O(n) time Can we do better? How?

Binary Heap: Definition Binary heap. Almost complete binary tree filled on all levels, except last, where filled from left to right Min-heap ordered every child greater than (or equal to) parent 06 14 45 78 18 47 53 83 91 81 77 84 99 64 Max-heap is analogous (every child is smaller than its parent)

Binary Heap: Properties Properties. Min element is in root. Heap with N elements has height = log 2 N. In particular can obtain minimum element (ExtractMin) in O(1) 14 06 45 N = 14 Height = 3 78 18 47 53 83 91 81 77 84 99 64

Binary Heap: Properties Properties. Min element is in root. Heap with N elements has height = log 2 N. In particular can obtain minimum element (ExtractMin) in O(1) 14 06 45 N = 14 Height = 3 78 18 47 53 83 91 81 77 84 99 64

Binary Heaps: Array Implementation Implementing binary heaps Use an array: no need for explicit parent or child pointers. Parent(i) = i/2 Left(i) = 2i Right(i) = 2i + 1 Only important properties for us: 1. Last level of the tree is occupied from left to right 2. We can find the first (leftmost) empty space in constant time (keep track of first empty space with an integer firstempty) 06 1 14 45 2 3 78 18 47 53 4 5 6 7 83 91 81 77 84 99 64 8 9 10 11 12 13 14

Binary Heap: Insertion Insert element x into heap. Insert into fist available slot. Bubble up until it's heap ordered. 06 14 45 78 18 47 53 83 91 81 77 84 99 64 next free slot

Binary Heap: Insertion Insert element x into heap. Insert into first available slot. Bubble up until it's heap ordered. 06 swap with parent 14 45 78 18 47 53 83 91 81 77 84 99 64

Binary Heap: Insertion Insert element x into heap. Insert into first available slot. Bubble up until it's heap ordered. 06 swap with parent 14 45 78 18 47 83 91 81 77 84 99 64 53

Binary Heap: Insertion Insert element x into heap. Insert into first available slot. Bubble up until it's heap ordered. Q: What is the time complexity of Insert? A: O(log N) operations 06 stop: heap ordered 14 78 18 47 45 83 91 81 77 84 99 64 53

Binary Heap: Decrease Key Decrease key of element x to k. Bubble up until it's heap ordered. O(log N) operations. 06 14 78 18 47 45 83 91 81 77 84 99 64 53

Binary Heap: Delete Min Delete minimum element from heap. Exchange root with any leaf (rightmost one is easy to find) Delete this leaf Bubble root down until it's heap ordered, exchanging it with smallest child 06 14 78 18 47 45 83 91 81 77 84 99 64 53

Binary Heap: Delete Min Delete minimum element from heap. Exchange root with any leaf (rightmost one is easy to find) Delete this leaf Bubble root down until it's heap ordered, exchanging it with smallest child 53 14 78 18 47 45 83 91 81 77 84 99 64 06

Binary Heap: Delete Min Delete minimum element from heap. Exchange root with any leaf (rightmost one is easy to find) Delete this leaf Bubble root down until it's heap ordered, exchanging it with smallest child 53 exchange with left child 14 78 18 47 45 83 91 81 77 84 99 64

Binary Heap: Delete Min Delete minimum element from heap. Exchange root with any leaf (rightmost one is easy to find) Delete this leaf Bubble root down until it's heap ordered, exchanging it with smallest child 14 exchange with right child 53 78 18 47 45 83 91 81 77 84 99 64

Binary Heap: Delete Min Delete minimum element from heap. Exchange root with any leaf (rightmost one is easy to find) Delete this leaf Bubble root down until it's heap ordered, exchanging it with smallest child Q: Why do we exchange with smallest child? A: Otherwise can violate heap property 14 stop: heap ordered 18 78 53 47 45 83 91 81 77 84 99 64

Binary Heap: Delete Min Delete minimum element from heap. Exchange root with any leaf (rightmost one is easy to find) Delete this leaf Bubble root down until it's heap ordered, exchanging it with smallest child Q: What is the time complexity of DeleteMin? A: O(log N) operations. 14 stop: heap ordered 18 78 53 47 45 83 91 81 77 84 99 64

Priority Queues Solution 1. Use a sorted list ExtractMin: O(1) time Insert: O(n) time DeleteMin: O(1) time Solution 2. Use a list with the pair with minimum p at the first position ExtractMin: O(1) time Insert: O(1) time DeleteMin: O(n) time Solution 3. Binary Heap ExtractMin: O(1) time Insert: O(log n) time DeleteMin: O(log n) time

Exercise Exercise: Can we use use the procedures we know (Insert, ExtractMin, DeleteMin, DecreaseKey) to implement the IncreaseKey(x,k) that increases the key of an element x to value k? If so, analyze the complexity of this new operation. Solution: One possibility is to remove element x and add it with key k. To remove this value we can: 1) Obtain the minimum MIN using ExtractMin 2) reduce the key of x to MIN-1 using DecreaseKey (so now x is minimum) 3) Apply RemoveMin to remove it The total complexity is O(log n), since it uses 4 operations that are at most O(log n).

Application: Heapsort Q: Can we sort N numbers using a Binary Heap? Insert N items into a binary min-heap O ( N log N) Perform N delete-min operations. O(N log N) Overall O(N log N) sort. Obs: If you use a max-heap can do with no extra storage (in-place)

Exercice Run the execution of Heapsort over list of numbers 18 25 41 34 10 52 50 48

Building a Heap In Heapsort, we just built a heap for n numbers by inserting them one at a time Time complexity of this procedure: O(n log n) Q: Can we build a heap faster? Bottleneck: When adding the last few nodes, each may move a lot up in the heap, costs too much 06 14 78 18 47 45 83 91 81

Building a Heap in O(n) Idea: Move nodes down instead of up Operation down(node): keeps exchanging node with smallest child until it is in the right position, that is, has smaller priorities than its children Building a Heap of numbers a1, a2, an in O(n): HeapBuild1 (Cormen) Make an almost complete binary tree with numbers in any position Traverse tree from bottom up applying down(node)

Example: Numbers 14, 06,, 78, 18 Building a Heap in O(n) Apply down() to node with 06 78 18 14 06

Example: Numbers 14, 06,, 78, 18 Building a Heap in O(n) Apply down() to node with 06 78 18 14 06

Example: Numbers 14, 06,, 78, 18 Building a Heap in O(n) Apply down() to node with 14 78 18 14 06

Example: Numbers 14, 06,, 78, 18 Building a Heap in O(n) Apply down() to node with 78 18 14 06

Example: Numbers 14, 06,, 78, 18 Building a Heap in O(n) Apply down() to node with 18 78 18 14 06

Example: Numbers 14, 06,, 78, 18 Building a Heap in O(n) Apply down() to node with 18 78 06 14 18

Example: Numbers 14, 06,, 78, 18 Building a Heap in O(n) Apply down() to node with 78 twice 78 06 14 18

Example: Numbers 14, 06,, 78, 18 Building a Heap in O(n) Apply down() to node with 78 twice 06 14 78 18

Building a Heap in O(n): Analysis Q: Quantos nós temos no nível i de baixo pra cima? Observação: Para i>0, no i-ésimo nível do heap de baixo para cima temos no máximo n / 2 i-1 nós O heap tem = log 2 n níveis. No nível 0, de baixo para cima, temos no mínimo 1 e no máximo N nós. Todos os niveis excetos os dois últimos tem metade dos nós do nível imediatamente abaixo

Building a Heap in O(n): Analysis Custo do down(node): se node está no nível i de baixo para cima, esse down custa O(i) operações Custo total logn i. i 1 n i 2 ( n)

Building a Heap in O(n): Analysis Custo do down(node): se node está no nível i de baixo para cima, esse down custa O(i) operações Custo total logn i. i 1 n i 2 ( n)

Exercise Exercicio: Seja S um conjunto de n numeros reais distintos. Explique como seria um algoritmo eficiente para encontrar os n menores numeros do conjunto S e analise sua complexidade. Quanto mais eficiente o algoritmo melhor. Solucao: Crie uma min-heap com os elementos de S e aplique ExtractMin n vezes; retorne esses elementos removidos Complexidade: O(n) pra montar o heap, O( n. log(n)) = O(n) para remover of elementos => total: O(n)