Containers: Priority Queues

Similar documents
Containers: Priority Queues. Jordi Cortadella and Jordi Petit Department of Computer Science

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

Sorting and Searching

The smallest element is the first one removed. (You could also define a largest-first-out priority queue)

Priority queues. Priority queues. Priority queue operations

Sorting and Searching

The beautiful binary heap.

Containers: Queue and List. Jordi Cortadella and Jordi Petit Department of Computer Science

PRIORITY QUEUES AND HEAPS

Containers: Stack. The Stack ADT. The Stack ADT. The Stack ADT

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science

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

Sorting vectors. Sorting. Sorting. Sorting. Another common task: sort v[a..b] Let T be a type with a operation, which is a total order.

PRIORITY QUEUES AND HEAPS

Programming II (CS300)

Heaps, Heap Sort, and Priority Queues.

CH 8. HEAPS AND PRIORITY QUEUES

Data Structures and Algorithms

CH. 8 PRIORITY QUEUES AND HEAPS

Tables and Priority Queues

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

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

CSE 2123: Collections: Priority Queues. Jeremy Morris

DataStruct 8. Heaps and Priority Queues

Abstract vs concrete data structures HEAPS AND PRIORITY QUEUES. Abstract vs concrete data structures. Concrete Data Types. Concrete data structures

CE 221 Data Structures and Algorithms

CSE 214 Computer Science II Heaps and Priority Queues

PRIORITY QUEUES AND HEAPS

Programming II (CS300)

Draw the resulting binary search tree. Be sure to show intermediate steps for partial credit (in case your final tree is incorrect).

Priority Queues (Heaps)

Priority queues. Priority queues. Priority queue operations

Priority Queues (Heaps)

Announcements HEAPS & PRIORITY QUEUES. Abstract vs concrete data structures. Concrete data structures. Abstract data structures

Priority Queues and Binary Heaps

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

Sorting Pearson Education, Inc. All rights reserved.

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

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

9. Heap : Priority Queue

Algorithms and Data Structures

CMSC 341 Lecture 14: Priority Queues, Heaps

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

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

HEAPS & PRIORITY QUEUES

HEAPS: IMPLEMENTING EFFICIENT PRIORITY QUEUES

For loops, nested loops and scopes. Jordi Cortadella Department of Computer Science

CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators)

CSE 373 Data Structures and Algorithms. Lecture 15: Priority Queues (Heaps) III

Data Structures and Algorithms for Engineers

CSCI 136 Data Structures & Advanced Programming. Lecture 22 Fall 2018 Instructor: Bills

The heap is essentially an array-based binary tree with either the biggest or smallest element at the root.

Priority Queues. 04/10/03 Lecture 22 1

Outline. For loops, nested loops and scopes. Calculate x y. For loops. Scopes. Nested loops. Algorithm: repeated multiplication x x x x

Priority queue ADT Heaps. Lecture 21

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

DATA STRUCTURES AND ALGORITHMS

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

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

Stores a collection of elements each with an associated key value

Binary Heaps in Dynamic Arrays

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

Priority Queues and Huffman Trees

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

INFO1x05 Tutorial 6. Exercise 1: Heaps and Priority Queues

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

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

Priority Queues. Chapter 9

Heaps Goodrich, Tamassia. Heaps 1

Algorithm Analysis. Jordi Cortadella and Jordi Petit Department of Computer Science

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

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

Heaps in C. CHAN Hou Pong, Ken CSCI2100 Data Structures Tutorial 7

Data Structures Brett Bernstein

CS350: Data Structures Heaps and Priority Queues

Binary Search Trees. BinaryTree<E> Class (cont.) Section /27/2017

CSE 373 Spring 2010: Midterm #1 (closed book, closed notes, NO calculators allowed)

CSCI2100B Data Structures Heaps

CS2 Algorithms and Data Structures Note 6

CSE 373 Autumn 2010: Midterm #2 (closed book, closed notes, NO calculators allowed)

Lecture 13: AVL Trees and Binary Heaps

Expression Trees and the Heap

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

Data Structures and Algorithms

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

Chapter 6 Heapsort 1

CS 310: Priority Queues and Binary Heaps

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

CSCI Trees. Mark Redekopp David Kempe

Priority Queues, Binary Heaps, and Heapsort

Figure 1: A complete binary tree.

Name Section Number. CS210 Exam #3 *** PLEASE TURN OFF ALL CELL PHONES*** Practice

Procedure Aim: To implement operations on binary heap. BINARY HEAP A binary heap is a complete binary tree which satisfies the heap ordering property.

CS165: Priority Queues, Heaps

Priority Queues Heaps Heapsort

binary tree empty root subtrees Node Children Edge Parent Ancestor Descendant Path Depth Height Level Leaf Node Internal Node Subtree

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

Heaps. A complete binary tree can be easily stored in an array - place the root in position 1 (for convenience)

Merge Sort Goodrich, Tamassia Merge Sort 1

Trees. A tree is a directed graph with the property

Transcription:

A priority queue Containers: Priority Queues A priority queue is a queue in which each element has a priority. Elements with higher priority are served before elements with lower priority. It can be implemented as a vector or a linked list. For a queue with n elements: Insertion is O(n). Extraction is O. Jordi Cortadella and Jordi Petit Department of Computer Science A more efficient implementation can be proposed in which insertion and extraction are O(log n): binary heap. Binary Heap Containers: Priority Queues Dept. CS, UPC Binary Heap Complete binary tree (except at the bottom level). Height h: between h and h+ nodes. For N nodes, the height is O(log N). It can be represented in a vector. 0 6 7 9 0 Locations in the vector: i i i + i (even) 0 6 7 9 0 iτ i + (odd) Heap-Order Property: the key of the parent of X is smaller than (or equal to) the key in X. Containers: Priority Queues Dept. CS, UPC Containers: Priority Queues Dept. CS, UPC

Binary Heap Binary Heap: insert Insert in the last location and bubble up Two main operations on a binary heap: Insert a new element Remove the min element Both operations must preserve the properties of the binary heap: Completeness Heap-Order property done! Containers: Priority Queues Dept. CS, UPC Binary Heap: remove min Containers: Priority Queues Dept. CS, UPC 6 Binary Heap: remove min Extract the min element and move the last one to the root of the heap and bubble down done! Containers: Priority Queues Dept. CS, UPC 7 Containers: Priority Queues Dept. CS, UPC

Binary Heap: implementation Binary Heap: implementation // Elem must be a comparable type template <typename Elem> class PriorityQueue { private: vector<elem> v; // Table for the heap (location 0 not used) public: // Constructor (one fake element in the vector) PriorityQueue() { v.push_back(elem()); /** Number of elements in the queue */ int size() { return v.size() - ; // The 0 location does not count /** Checks whether the queue is empty */ bool empty() { return size() == 0; Containers: Priority Queues Dept. CS, UPC 9 private: Binary Heap: implementation /** Bubbles up the element at location i */ void bubble_up(int i) { if (i!= and v[i/] > v[i]) { swap(v[i], v[i/]); bubble_up(i/); /** Bubbles down the element at location i */ void bubble_down(int i) { int n = size(); int c = *i; if (c <= n) { if (c+ <= n and v[c+] < v[c]) c++; if (v[i] > v[c]) { swap(v[i],v[c]); bubble_down(c); public: /** Returns the min element of the queue */ Elem minimum() { assert(not empty()); return v[]; /** Inserts and element into the queue */ void insert(const Elem& x) { v.push_back(x); // Put element at the bottom bubble_up(size()); // and bubble up /** Extracts and returns the min element from the queue */ Elem remove_min () { assert(not empty()); Elem x = v[]; // Store the element at the root v[] = v.back(); // Move the last element to the root v.pop_back(); bubble_down(); // and bubble down return x; Containers: Priority Queues Dept. CS, UPC 0 Binary Heap: complexity Bubble up/down operations do at most h swaps, where h is the height of the tree and Therefore: h = log N Getting the min element is O() Inserting a new element is O(log N) Removing the min element is O(log N) Containers: Priority Queues Dept. CS, UPC Containers: Priority Queues Dept. CS, UPC

Binary Heap: other operations Building a heap from a set of elements Let us assume that we have a method to know the location of every key in the heap. Increase/decrease key: Modify the value of one element in the middle of the heap. If decreased bubble up. If increased bubble down. Heaps are sometimes constructed from an initial collection of N elements. How much does it cost to create the heap? Obvious method: do N insert operations. Complexity: O(N log N) Can it be done more efficiently? Remove one element: Set value to, bubble up and remove min element. Containers: Priority Queues Dept. CS, UPC Building a heap from a set of elements Containers: Priority Queues Dept. CS, UPC Building a heap: implementation 0 7 bubble down 0 7 // Constructor from a collection of items PriorityQueue(const vector<elem>& items) { v.push_back(elem()); for (auto& e: items) v.push_back(e); for (int i = size()/; i > 0; --i) bubble_down(i); 0 7 0 7 Sum of the heights of all nodes: node with height h nodes with height h nodes with height h i nodes with height h i h S = i (h i) i=0 S = h + h + h + h + h + + h () 0 7 0 7 S = h + h + h + h + + h () Subtract the two equations: S = h + + + + + h + h = h+ h + = O(N) 6 6 0 9 7 0 9 7 Containers: Priority Queues Dept. CS, UPC A heap can be built from a collection of items in linear time. Containers: Priority Queues Dept. CS, UPC

Heap sort template <typename T> void heapsort(vector<t>& v) { PriorityQueue<T> heap(v); for (T& e: v) e = heap.remove_min(); Exercises Given the binary heap implemented in the following vector, draw the tree represented by the vector and the corresponding vector after inserting the element and removing the minimum: 7 9 7 9 Complexity: O n log n Building the heap: O(n) Each removal is O log n, executed n times. The k-th element of n sorted vectors. Let us consider n vectors sorted in ascending order. Design an algorithm with cost Θ(k log n + n) that finds the k-th global smallest element. Containers: Priority Queues Dept. CS, UPC 7 Containers: Priority Queues Dept. CS, UPC