Heaps, Heap Sort, and Priority Queues.

Similar documents
Priority Queues (Heaps)

Priority Queues (Heaps)

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

CE 221 Data Structures and Algorithms

CMSC 341 Lecture 14: Priority Queues, Heaps

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

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

Sorting and Searching

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

Sorting and Searching

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

Algorithms and Data Structures

CSCI2100B Data Structures Heaps

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

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

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

COMP : Trees. COMP20012 Trees 219

CS350: Data Structures Heaps and Priority Queues

Priority Queues Heaps Heapsort

Chapter 6 Heaps. Introduction. Heap Model. Heap Implementation

CSE 373: Data Structures and Algorithms

CMSC 341. Binary Heaps. Priority Queues

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

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

Trees, Binary Trees, and Binary Search Trees

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

Priority Queues Heaps Heapsort

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

Priority Queues. Chapter 9

Data Structures Lesson 9

Figure 1: A complete binary tree.

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

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

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

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

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

Data Structures and Algorithms

Binary Heaps. COL 106 Shweta Agrawal and Amit Kumar

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

CSE373: Data Structures & Algorithms Lecture 9: Priority Queues. Aaron Bauer Winter 2014

CSE 332: Data Structures & Parallelism Lecture 3: Priority Queues. Ruth Anderson Winter 2019

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

CSE373: Data Structures & Algorithms Priority Queues

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

Algorithms and Data Structures

Figure 1: A complete binary tree.

Recall: Properties of B-Trees

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

Tables and Priority Queues

Implementations III 1

CS165: Priority Queues, Heaps

CS 310: Priority Queues and Binary Heaps

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

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

Priority Queues. 04/10/03 Lecture 22 1

Programming II (CS300)

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

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

CH 8. HEAPS AND PRIORITY QUEUES

CSE332: Data Abstractions Lecture 4: Priority Queues; Heaps. James Fogarty Winter 2012

CH. 8 PRIORITY QUEUES AND HEAPS

HEAPS: IMPLEMENTING EFFICIENT PRIORITY QUEUES

Appendix A and B are also worth reading.

CS2223: Algorithms Sorting Algorithms, Heap Sort, Linear-time sort, Median and Order Statistics

Properties of red-black trees

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

Binary Heaps. CSE 373 Data Structures Lecture 11

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

COSC160: Data Structures Heaps. Jeremy Bolton, PhD Assistant Teaching Professor

Heaps. 2/13/2006 Heaps 1

BINARY HEAP cs2420 Introduction to Algorithms and Data Structures Spring 2015

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

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

Module 2: Priority Queues

Trees. A tree is a directed graph with the property

AMORTIZED ANALYSIS. Announcements. CSE 332 Data Abstractions: Priority Queues, Heaps, and a Small Town Barber. Today.

Data Structures Week #8. Heaps (Priority Queues)

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

Module 2: Priority Queues

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

Administration CSE 326: Data Structures

CSC263 Week 2. Larry Zhang

Tables, Priority Queues, Heaps

Adam Blank Lecture 3 Winter 2017 CSE 332. Data Structures and Parallelism

Priority queues. Priority queues. Priority queue operations

Stores a collection of elements each with an associated key value

Heaps Goodrich, Tamassia. Heaps 1

CSCI-1200 Data Structures Spring 2016 Lecture 22 Priority Queues, part II (& Functors)

The beautiful binary heap.

Binary heaps (chapters ) Leftist heaps

ECE 242 Data Structures and Algorithms. Heaps I. Lecture 22. Prof. Eric Polizzi

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

Priority Queues and Heaps

Priority Queues and Binary Heaps

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

Operations. Priority Queues & Heaps. Prio-Q as Array. Niave Solution: Prio-Q As Array. Prio-Q as Sorted Array. Prio-Q as Sorted Array

Design and Analysis of Algorithms

Section 4 SOLUTION: AVL Trees & B-Trees

Unit #2: Priority Queues

Data Structures and Algorithms for Engineers

Transcription:

Heaps, Heap Sort, and Priority Queues

Sorting III / Slide 2 Background: Binary Trees Has a root at the topmost level Each node has zero, one or two children A node that has no child is called a leaf For a node x, we denote the left child, right child and the parent of x as left(x), right(x) and parent(x), respectively. Parent(x) x left(x)right(x) leaf root leaf leaf

Sorting III / Slide 3 Struct Node { double element; // the data Node* left; // left child Node* right; // right child // Node* parent; // parent } A binary tree can be naturally implemented by pointers. class Tree { public: Tree(); Tree(const Tree& t); ~Tree(); // constructor // destructor bool empty() const; double root(); // decomposition (access functions) Tree& left(); Tree& right(); // Tree& parent(double x); // update void insert(const double x); // compose x into a tree void remove(const double x); // decompose x from a tree private: } Node* root;

Sorting III / Slide 4 Height (Depth) of a Binary Tree The number of edges on the longest path from the root to a leaf. Height = 4

Sorting III / Slide 5 Background: Complete Binary Trees A complete binary tree is the tree Where a node can have 0 (for the leaves) or 2 children and All leaves are at the same depth height no. of nodes 0 1 1 2 2 4 3 8 No. of nodes and height A complete binary tree with N nodes has height O(logN) A complete binary tree with height d has, in total, 2 d+1-1 nodes d 2 d

Sorting III / Slide 6 Proof: O(logN) Height Proof: a complete binary tree with N nodes has height of O(logN) 1. Prove by induction that number of nodes at depth d is 2 d 2. Total number of nodes of a complete binary tree of depth d is 1 + 2 + 4 + 2 d = 2 d+1-1 3. Thus 2 d+1-1 = N 4. d = log(n+1)-1 = O(logN) Side notes: the largest depth of a binary tree of N nodes is O(N)

Sorting III / Slide 7 (Binary) Heap Heaps are almost complete binary trees All levels are full except possibly the lowest level If the lowest level is not full, then nodes must be packed to the left Pack to the left

Sorting III / Slide 8 1 2 5 4 3 6 A heap 4 2 5 1 3 6 Not a heap Heap-order property: the value at each node is less than or equal to the values at both its descendants --- Min Heap It is easy (both conceptually and practically) to perform insert and deletemin in heap if the heap-order property is maintained

Sorting III / Slide 9 Structure properties Has 2 h to 2 h+1-1 nodes with height h The structure is so regular, it can be represented in an array and no links are necessary!!! Use of binary heap is so common for priority queue implementations, thus the word heap is usually assumed to be the implementation of the data structure

Sorting III / Slide 10 Heap Properties Heap supports the following operations efficiently Insert in O(logN) time Locate the current minimum in O(1) time Delete the current minimum in O(log N) time

Sorting III / Slide 11 Array Implementation of Binary Heap A B D E F G C A B C D E F G H I J 0 1 2 3 4 5 6 7 8 H I J For any element in array position i The left child is in position 2i The right child is in position 2i+1 The parent is in position floor(i/2) A possible problem: an estimate of the maximum heap size is required in advance (but normally we can resize if needed) Note: we will draw the heaps as trees, with the implication that an actual implementation will use simple arrays Side notes: it s not wise to store normal binary trees in arrays, because it may generate many holes

Sorting III / Slide 12 class Heap { public: Heap(); Heap(const Heap& t); ~Heap(); // constructor // destructor bool empty() const; double root(); // access functions Heap& left(); Heap& right(); Heap& parent(double x); // update void insert(const double x); // compose x into a heap void deletemin(); // decompose x from a heap private: double* array; int array-size; int heap-size; }

Sorting III / Slide 13 Insertion Algorithm 1. Add the new element to the next available position at the lowest level 2. Restore the min-heap property if violated General strategy is percolate up (or bubble up): if the parent of the element is larger than the element, then interchange the parent and child. 1 1 1 2 5 2 5 2 2.5 swap 4 3 6 4 3 6 2.5 4 3 6 5 Insert 2.5 Percolate up to maintain the heap property

Sorting III / Slide 14 Insertion Complexity 7 9 8 A heap! 17 16 14 10 20 18 Time Complexity = O(height) = O(logN)

Sorting III / Slide 15 deletemin: First Attempt Algorithm 1. Delete the root. 2. Compare the two children of the root 3. Make the lesser of the two the root. 4. An empty spot is created. 5. Bring the lesser of the two children of the empty spot to the empty spot. 6. A new empty spot is created. 7. Continue

Sorting III / Slide 16 Example for First Attempt 1 2 5 4 3 6 2 5 4 3 6 2 4 3 6 5 1 3 5 4 6 Heap property is preserved, but completeness is not preserved!

Sorting III / Slide 17 deletemin 1. Copy the last number to the root (i.e. overwrite the minimum element stored there) 2. Restore the min-heap property by percolate down (or bubble down)

Sorting III / Slide 18

Sorting III / Slide 19 An Implementation Trick (see Weiss book) Implementation of percolation in the insert routine by performing repeated swaps: 3 assignment state-ments for a swap. 3d assignments if an element is percolated up d levels An enhancement: Hole digging with d+1 assignments (avoiding swapping!) 7 7 7 4 9 8 9 4 8 8 17 16 14 10 4 17 14 10 17 9 14 10 20 18 Dig a hole Compare 4 with 16 20 18 16 Compare 4 with 9 20 18 16 Compare 4 with 7

Sorting III / Slide 20 Insertion PseudoCode void insert(const Comparable &x) { //resize the array if needed if (currentsize == array.size()-1 array.resize(array.size()*2) //percolate up int hole = ++currentsize; for (; hole>1 && x<array[hole/2]; hole/=2) array[hole] = array[hole/2]; array[hole]= x; }

Sorting III / Slide 21 deletemin with Hole Trick The same hole trick used in insertion can be used here too 2 2 5 5 4 3 6 1. create hole tmp = 6 (last element) 2 4 3 6 2. Compare children and tmp bubble down if necessary 2 3 5 3 5 4 6 4 6 3. Continue step 2 until reaches lowest level 4. Fill the hole

Sorting III / Slide 22 deletemin PseudoCode void deletemin() { if (isempty()) throw UnderflowException(); //copy the last number to the root, decrease array size by 1 array[1] = array[currentsize--] percolatedown(1); //percolatedown from root } void percolatedown(int hole) //int hole is the root position { int child; Comparable tmp = array[hole]; //create a hole at root for( ; hold*2 <= currentsize; hole=child){ //identify child position child = hole*2; //compare left and right child, select the smaller one if (child!= currentsize && array[child+1] <array[child] child++; if(array[child]<tmp) //compare the smaller child with tmp array[hole] = array[child]; //bubble down if child is smaller else break; //bubble stops movement } array[hole] = tmp; //fill the hole }

Sorting III / Slide 23 Heap is an efficient structure Array implementation hole trick Access is done bit-wise, shift, bit+1,

Sorting III / Slide 24 Heapsort (1) Build a binary heap of N elements the minimum element is at the top of the heap (2) Perform N DeleteMin operations the elements are extracted in sorted order (3) Record these elements in a second array and then copy the array back

Sorting III / Slide 25 Build Heap Input: N elements Output: A heap with heap-order property Method 1: obviously, N successive insertions Complexity: O(NlogN) worst case

Sorting III / Slide 26 Heapsort Running Time Analysis (1) Build a binary heap of N elements repeatedly insert N elements O(N log N) time (there is a more efficient way, check textbook p223 if interested) (2) Perform N DeleteMin operations Each DeleteMin operation takes O(log N) O(N log N) (3) Record these elements in a second array and then copy the array back O(N) Total time complexity: O(N log N) Memory requirement: uses an extra array, O(N)

Sorting III / Slide 27 Heapsort: in-place, no extra storage Observation: after each deletemin, the size of heap shrinks by 1 We can use the last cell just freed up to store the element that was just deleted after the last deletemin, the array will contain the elements in decreasing sorted order To sort the elements in the decreasing order, use a min heap To sort the elements in the increasing order, use a max heap the parent has a larger element than the child

Sorting III / Slide 28 Sort in increasing order: use max heap Delete 97

Sorting III / Slide 29 Delete 16 Delete 14 Delete 10 Delete 9 Delete 8

Sorting III / Slide 30

Sorting III / Slide 31 One possible Heap ADT Template <typename Comparable> class BinaryHeap { public: BinaryHeap(int capacity=100); explicit BinaryHeap(const vector<comparable> &items); bool isempty() const; void insert(const Comparable &x); void deletemin(); void deletemin(comparable &minitem); void makeempty(); private: int currentsize; //number of elements in heap vector<comparable> array; //the heap array void buildheap(); void percolatedown(int hole); }

Sorting III / Slide 32 Priority Queue: Motivating Example 3 jobs have been submitted to a printer in the order A, B, C. Sizes: Job A 100 pages Job B 10 pages Job C -- 1 page Average waiting time with FIFO service: (100+110+111) / 3 = 107 time units Average waiting time for shortest-job-first service: (1+11+111) / 3 = 41 time units A queue be capable to insert and deletemin? Priority Queue

Sorting III / Slide 33 Priority Queue Priority queue is a data structure which allows at least two operations insert deletemin: finds, returns and removes the minimum elements in the priority queue deletemin Priority Queue insert Applications: external sorting, greedy algorithms

Sorting III / Slide 34 Possible Implementations Linked list Insert in O(1) Find the minimum element in O(n), thus deletemin is O(n) Binary search tree (AVL tree, to be covered later) Insert in O(log n) Delete in O(log n) Search tree is an overkill as it does many other operations Eerr, neither fit quite well

Sorting III / Slide 35 It s a heap!!!