Binary Heaps. CSE 373 Data Structures Lecture 11

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

Binary Heaps. COL 106 Shweta Agrawal and Amit Kumar

Recall: Properties of B-Trees

Administration CSE 326: Data Structures

CS350: Data Structures Heaps and Priority Queues

CSCI2100B Data Structures Heaps

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

Data Structures and Algorithms

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

9. Heap : Priority Queue

Priority Queues. Binary Heaps

CMSC 341 Lecture 14: Priority Queues, Heaps

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

Sorting and Searching

Sorting and Searching

Data Structures Lesson 9

Priority Queues Heaps Heapsort

CE 221 Data Structures and Algorithms

Algorithms and Data Structures

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

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

Chapter 6 Heaps. Introduction. Heap Model. Heap Implementation

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

Priority Queues (Heaps)

Priority Queues Heaps Heapsort

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

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

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

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

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

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

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

Priority Queues (Heaps)

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

Priority Queues and Heaps

Priority Queues and Binary Heaps

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

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

Figure 1: A complete binary tree.

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

CSE 373: Data Structures and Algorithms

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

Figure 1: A complete binary tree.

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

UNIT III BALANCED SEARCH TREES AND INDEXING

Priority queues. Priority queues. Priority queue operations

CMSC 341 Lecture 15 Leftist Heaps

CMSC 341 Lecture 15 Leftist Heaps

Heaps Goodrich, Tamassia. Heaps 1

Priority Queues. 04/10/03 Lecture 22 1

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

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

Design and Analysis of Algorithms

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

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

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

Binary Trees, Binary Search Trees

BINARY HEAP cs2420 Introduction to Algorithms and Data Structures Spring 2015

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

CSE373: Data Structures & Algorithms Priority Queues

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

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

Dictionaries. Priority Queues

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

COMP 103 RECAP-TODAY. Priority Queues and Heaps. Queues and Priority Queues 3 Queues: Oldest out first

COMP : Trees. COMP20012 Trees 219

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?

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

Data Structures in Java

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

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

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

CMSC 341 Leftist Heaps

Heaps. 2/13/2006 Heaps 1

CH 8. HEAPS AND PRIORITY QUEUES

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

Tables, Priority Queues, Heaps

CH. 8 PRIORITY QUEUES AND HEAPS

Module 2: Priority Queues

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

CMSC 341. Binary Heaps. Priority Queues

CompSci 201 Tree Traversals & Heaps

Programming II (CS300)

Algorithms and Data Structures

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)

Heaps. A heap is a certain kind of complete binary tree.

Topic: Heaps and priority queues

Stores a collection of elements each with an associated key value

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

Data Structures Week #8. Heaps (Priority Queues)

Heaps, Heap Sort, and Priority Queues.

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

8. Binary Search Tree

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

CSE 214 Computer Science II Heaps and Priority Queues

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

Multi-way Search Trees! M-Way Search! M-Way Search Trees Representation!

DATA STRUCTURES AND ALGORITHMS. Hierarchical data structures: AVL tree, Bayer tree, Heap

Course Review. Cpt S 223 Fall 2009

Transcription:

Binary Heaps CSE Data Structures Lecture

Readings and References Reading Sections.1-. //0 Binary Heaps - Lecture

A New Problem Application: Find the smallest ( or highest priority) item quickly Operating system needs to schedule jobs according to priority Doctors in ER take patients according to severity of injuries Event simulation (bank customers arriving and departing, ordered according to when the event happened) //0 Binary Heaps - Lecture

Priority Queue ADT Priority Queue can efficiently do: FindMin (and DeleteMin) Insert What if we use Lists: If sorted, what is the run time for Insert and FindMin? Unsorted? Binary Search Trees: What is the run time for Insert and FindMin? //0 Binary Heaps - Lecture

Less flexibility More speed Lists If sorted: FindMin is O(1) but Insert is O(N) If not sorted: Insert is O(1) but FindMin is O(N) Balanced Binary Search Trees (BSTs) Insert is O(log N) and FindMin is O(log N) BSTs look good but BSTs are efficient for all Finds, not just FindMin We only need FindMin //0 Binary Heaps - Lecture

Better than a speeding BST We can do better than Balanced Binary Search Trees? Very limited requirements: Insert, FindMin, DeleteMin FindMin is O(1) Insert is O(log N) DeleteMin is O(log N) //0 Binary Heaps - Lecture

Binary Heaps A binary heap is a binary tree that is: Complete: the tree is completely filled except possibly the bottom level, which is filled from left to right Satisfies the heap order property every node is less than or equal to its children or every node is greater than or equal to its children The root node is always the smallest node or the largest, depending on the heap order //0 Binary Heaps - Lecture

Heap order property A heap provides limited ordering information Each path is sorted, but the subtrees are not sorted relative to each other A binary heap is NOT a binary search tree -1 0 1 0 These are all valid binary heaps (minimum) 1 //0 Binary Heaps - Lecture

Binary Heap vs Binary Search Tree Binary Heap min value Binary Search Tree min value Parent is less than both left and right children Parent is greater than left child, less than right child //0 Binary Heaps - Lecture

Structure property A binary heap is a complete tree All nodes are in use except for possibly the right end of the bottom row //0 Binary Heaps - Lecture

Examples complete tree, heap order is "max" not complete complete tree, heap order is "min" complete tree, but min heap order is broken //0 Binary Heaps - Lecture

Array Implementation of Heaps (Implicit Pointers) Root node = A[1] Children of A[i] = A[i], A[i + 1] Keep track of current size N (number of nodes) value index - 0 1 N = //0 Binary Heaps - Lecture 1 1

FindMin and DeleteMin FindMin: Easy! Return root value A[1] Run time =? DeleteMin: Delete (and return) value at root node //0 Binary Heaps - Lecture 1

DeleteMin Delete (and return) value at root node //0 Binary Heaps - Lecture 1

Maintain the Structure Property We now have a Hole at the root Need to fill the hole with another value When we get done, the tree will have one less node and must still be complete //0 Binary Heaps - Lecture 1

Maintain the Heap Property The last value has lost its node we need to find a new place for it We can do a simple insertion sort operation to find the correct place for it in the tree //0 Binary Heaps - Lecture 1

DeleteMin: Percolate Down?? Keep comparing with children A[i] and A[i + 1] Copy smaller child up and go down one level Done if both children are item or reached a leaf node What is the run time? //0 Binary Heaps - Lecture 1

Percolate Down PercDown(i:integer, x :integer): { // N is the number of entries in queue// j : integer; Case{ i > N : A[i] := x; //at bottom// i = N : if A[i] < x then A[i] := A[i]; A[i] := x; else A[i] := x; i < N : if A[i] < A[i+1] then j := i; else j := i+1; if A[j] < x then A[i] := A[j]; PercDown(j,x); else A[i] := x; }} //0 Binary Heaps - Lecture 1

DeleteMin: Run Time Analysis Run time is O(depth of heap) A heap is a complete binary tree Depth of a complete binary tree of N nodes? depth = log (N) Run time of DeleteMin is O(log N) //0 Binary Heaps - Lecture 1

Insert Add a value to the tree Structure and heap order properties must still be correct when we are done //0 Binary Heaps - Lecture 0

Maintain the Structure Property The only valid place for a new node in a complete tree is at the end of the array We need to decide on the correct value for the new node, and adjust the heap accordingly //0 Binary Heaps - Lecture 1

Maintain the Heap Property The new value goes where? We can do a simple insertion sort operation to find the correct place for it in the tree //0 Binary Heaps - Lecture

Insert: Percolate Up??? Start at last node and keep comparing with parent A[i/] If parent larger, copy parent down and go up one level Done if parent item or reached top node A[1] Run time? //0 Binary Heaps - Lecture

Insert: Done Run time? //0 Binary Heaps - Lecture

PercUp Class participation Define PercUp which percolates new entry to correct spot. Note: the parent of i is i/ PercUp(i : integer, x : integer): {???? } //0 Binary Heaps - Lecture

Sentinel Values Every iteration of Insert needs to test: if it has reached the top node A[1] if parent item Can avoid first test if A[0] contains a very large negative value sentinel - < item, for all items Second test alone always stops at top - value index - 0 1 1 1 //0 Binary Heaps - Lecture

Binary Heap Analysis Space needed for heap of N nodes: O(MaxN) An array of size MaxN, plus a variable to store the size N, plus an array slot to hold the sentinel Time FindMin: O(1) DeleteMin and Insert: O(log N) BuildHeap from N inputs : O(N) //0 Binary Heaps - Lecture

Build Heap N= BuildHeap { for i = N/ to 1 by 1 PercDown(i,A[i]) } 1 //0 Binary Heaps - Lecture

Build Heap //0 Binary Heaps - Lecture

Build Heap //0 Binary Heaps - Lecture 0

Analysis of Build Heap Assume N = K 1 Level 1: k -1 steps for 1 item Level : k - steps of items Level : k - steps for items Level i : k - i steps for i-1 items Total Steps k1 i1 ( k i O(N) ) i1 k k -1 //0 Binary Heaps - Lecture 1

Other Heap Operations Find(X, H): Find the element X in heap H of N elements What is the running time? O(N) FindMax(H): Find the maximum element in H What is the running time? O(N) We sacrificed performance of these operations in order to get O(1) performance for FindMin //0 Binary Heaps - Lecture

Other Heap Operations DecreaseKey(P,,H): Decrease the key value of node at position P by a positive amount. eg, to increase priority First, subtract from current value at P Heap order property may be violated so percolate up to fix Running Time: O(log N) //0 Binary Heaps - Lecture

Other Heap Operations IncreaseKey(P,,H): Increase the key value of node at position P by a positive amount. eg, to decrease priority First, add to current value at P Heap order property may be violated so percolate down to fix Running Time: O(log N) //0 Binary Heaps - Lecture

Other Heap Operations Delete(P,H): E.g. Delete a job waiting in queue that has been preemptively terminated by user Use DecreaseKey(P,,H) followed by DeleteMin Running Time: O(log N) //0 Binary Heaps - Lecture

Other Heap Operations Merge(H1,H): Merge two heaps H1 and H of size O(N). H1 and H are stored in two arrays. Can do O(N) Insert operations: O(N log N) time Better: Copy H at the end of H1 and use BuildHeap. Running Time: O(N) //0 Binary Heaps - Lecture

PercUp Solution PercUp(i : integer, x : integer): { if i = 1 then A[1] := x else if A[i/] < x then A[i] := x; else A[i] := A[i/]; Percup(i/,x); } //0 Binary Heaps - Lecture