CSE 214 Computer Science II Heaps and Priority Queues

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

CSE 214 Computer Science II Introduction to Tree

CE 221 Data Structures and Algorithms

Data Structures and Algorithms

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

CS350: Data Structures Heaps and Priority Queues

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

Programming II (CS300)

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

Name CPTR246 Spring '17 (100 total points) Exam 3

Programming II (CS300)

CSE 230 Intermediate Programming in C and C++ Binary Tree

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

- Alan Perlis. Topic 24 Heaps

9. Heap : Priority Queue

" Which data Structure to extend to create a heap? " Two binary tree extensions are needed in a heap. n it is a binary tree (a complete one)

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

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

Priority Queue. How to implement a Priority Queue? queue. priority queue

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

CS165: Priority Queues, Heaps

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

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

CMSC 341 Lecture 14: Priority Queues, Heaps

CS302 - Data Structures using C++

Priority queues. Priority queues. Priority queue operations

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

Partha Sarathi Manal

Algorithms and Data Structures

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

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

Priority Queues and Binary Heaps

The number of nodes, N, in a binary tree of height, h is: 2 N 2 The height of a binary tree is: h =

Chapter 6 Heapsort 1

ITI Introduction to Computing II

ITI Introduction to Computing II

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

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

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

Programming II (CS300)

Multi-way Search Trees. (Multi-way Search Trees) Data Structures and Programming Spring / 25

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

Sorting and Searching

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

Design and Analysis of Algorithms

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

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

Priority Queues. Binary Heaps

CSE 214 Computer Science II Searching

Sorting and Searching

Priority Queues. 04/10/03 Lecture 22 1

Heapsort. Heap data structure

Module 2: Priority Queues

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

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

Module 2: Priority Queues

Properties of a heap (represented by an array A)

Priority queues. Priority queues. Priority queue operations

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

CSE 230 Computer Science II (Data Structure) Introduction

Priority Queues (Heaps)

Heaps. 2/13/2006 Heaps 1

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

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

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

Unit #2: Priority Queues

CMSC 341 Lecture 15 Leftist Heaps

Priority Queues (Heaps)

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

Lecture 9: Balanced Binary Search Trees, Priority Queues, Heaps, Binary Trees for Compression, General Trees

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

CMSC 341 Lecture 15 Leftist Heaps

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

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

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

Administration CSE 326: Data Structures

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

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

CSE 373: Data Structures and Algorithms

CMSC 341 Leftist Heaps

CSC 421: Algorithm Design Analysis. Spring 2013

CSE 214 Computer Science II Final Review II

CSCI 200 Lab 11 A Heap-Based Priority Queue

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

Priority Queues Heaps Heapsort

CmpSci 187: Programming with Data Structures Spring 2015

cs2010: algorithms and data structures

Leftist Heaps and Skew Heaps. (Leftist Heaps and Skew Heaps) Data Structures and Programming Spring / 41

Recall: Properties of B-Trees

Computer Science 136 Exam 2

Topic: Heaps and priority queues

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

INF2220: algorithms and data structures Series 1

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

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

CSE 373 Winter 2009: Midterm #1 (closed book, closed notes, NO calculators allowed)

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

Binary Heaps in Dynamic Arrays

Heaps and Priority Queues

Before class. BSTs, Heaps, and PQs 2/26/13 1. Open TreeNodeExample.java Change main to:

Transcription:

CSE 214 Computer Science II Heaps and Priority Queues Spring 2018 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu http://www3.cs.stonybrook.edu/~cse214/sec02/

Introduction to Heaps In last few lectures you have learned about binary trees and binary search trees (BST) BST is a certain type of binary tree where the nodes in the left subtree have values less than the root and the nodes in the right subtree have values greater than the root. No duplicates are allowed in a BST Heap or Binary Heap is a certain kind of Complete Binary Tree Shebuti Rayana (CS, Stony Brook University) 2

Heaps Root A heap is a certain kind of complete binary tree. When a complete binary tree is built, its first node must be the root.

Heaps Complete binary tree. Left child of the root The second node is always the left child of the root.

Heaps Complete binary tree. Right child of the root The third node is always the right child of the root.

Heaps Complete binary tree. The next nodes always fill the next level from left-to-right.

Heaps Complete binary tree. The next nodes always fill the next level from left-to-right.

Heaps Complete binary tree. The next nodes always fill the next level from left-to-right.

Heaps Complete binary tree. The next nodes always fill the next level from left-to-right.

Heaps Complete binary tree.

Heap Property A Binary Heap is a complete binary tree which satisfies the heap ordering property. The ordering can be one of two types: the min-heap property: the value of each node is greater than or equal to the value of its parent, with the minimum-value element at the root. the max-heap property: the value of each node is less than or equal to the value of its parent, with the maximum-value element at the root. 39 95 53 72 61 83 Min-heap 61 95 83 53 39 72 Max-heap 11

Is this a Max-heap? 95 61 83 53 39 72 16 24 48 NOT Complete Shebuti Rayana (CS, Stony Brook University) 12

Is this a Max-heap? 95 NO 53 83 61 39 72 16 24 48 Shebuti Rayana (CS, Stony Brook University) 13

Is this a Max-heap? 95 61 83 53 39 72 16 24 48 YES Shebuti Rayana (CS, Stony Brook University) 14

Characteristics of Heap In a heap the highest (or lowest) priority element is always stored at the root, hence the name "heap". A heap is not a sorted structure and can be regarded as partially ordered. As you see from the picture, there is no particular relationship among nodes on any given level, even among the siblings. Min-heap Max-heap Since a heap is a complete binary tree, it has a smallest possible height - a heap with N nodes always has O(log N) height. A heap is useful data structure when you need to remove the object with the highest (or lowest) priority. A common use of a heap is to implement a priority queue. 15

Storage of a Heap A complete binary tree can be uniquely represented by storing its level order traversal in an array. As heap (Min or Max) is a complete binary tree, we can use an array to hold the data of the heap. Store the root in position 0. For any node in position i, its left child (if any) is in position 2i + 1 its right child (if any) is in position 2i + 2 its parent (if any) is in position (i-1)/2 (integer division) Shebuti Rayana (CS, Stony Brook University) 16

Storage of a Max-heap 95 61 83 Left child: 2i+1 Right child: 2i+2 Parent: (i-1)/2 53 39 72 16 24 48 0 1 2 3 4 5 6 7 8 95 61 83 53 39 72 16 24 48 Shebuti Rayana (CS, Stony Brook University) 17

Important point for Implementation The links between the tree's nodes are not actually stored as reference, or in any other way. The only way we "know" that "the array is a tree" is from the way we manipulate the data. Shebuti Rayana (CS, Stony Brook University) 18

Basic Operations on Heaps Create an empty heap (constructor). Insert a data element into a heap (Min or Max). Delete the maximum data element from the Maxheap. Delete the minimum data element from the Minheap Shebuti Rayana (CS, Stony Brook University) 19

Array Implementation of Heap public class Heap { private int[] data; /*storage array*/ private int heapsize; /*current size*/ private int maxsize; /*capacity*/ public Heap(int maximumsize) { /*constructor*/ if (maximumsize < 1) maxsize = 100; else maxsize = maximumsize; data = new int[maxsize]; heapsize = 0; } public boolean isempty(){ if(heapsize == 0)return true; else return false; } public boolean isfull(){ if(heapsize == maxsize) return true; else return false; } } Shebuti Rayana (CS, Stony Brook University) 20

Inserting new element in Max-heap Place the new element in the first available position in the array. Compare the new element with its parent. If the new element is greater, then swap it with its parent. Continue this process until either the new element s parent is greater than or equal to the new element, or the new element reaches the root Shebuti Rayana (CS, Stony Brook University) 21

Inserting into a Max-heap 95 Insert 38 61 83 53 39 72 16 24 48 38 Does it hold the max-heap property? YES Insert element to the first available position Shebuti Rayana (CS, Stony Brook University) 22

Inserting into a Max-heap (cont.) 95 Insert 70 61 83 53 39 72 16 24 48 70 Does it hold the max-heap property? NO Insert element to the first available position Shebuti Rayana (CS, Stony Brook University) 23

Inserting into a Max-heap (cont.) 95 Insert 70 61 83 53 70 72 16 24 48 39 Shebuti Rayana (CS, Stony Brook University) 24

Inserting into a Max-heap (cont.) 95 Insert 70 70 83 53 61 72 16 24 48 39 Does it hold the max-heap property now? YES Shebuti Rayana (CS, Stony Brook University) 25

Inserting into a Max-heap public void insert(int item) { int position; if (isfull()) throw new Exception(); heapsize++; data[heapsize-1] = item; position = heapsize 1; while (position > 0 && data[position] > data[(position-1)/2]){ swap(position, (position-1)/2); position = (position-1) / 2; } } Shebuti Rayana (CS, Stony Brook University) 26

Deleting maximum element from a Max-heap Maximum element is stored in the root, so place the root element in a variable to return later. Move the last element in the deepest level to the root (reduce the size of the heap by 1). While the moved element has a value lower than one of its children, swap this value with the highest-valued child. Return the original root that was saved. Shebuti Rayana (CS, Stony Brook University) 27

Deleting maximum element from a Max-heap (cont.) 95 Delete 95 70 83 53 61 72 16 24 48 39 Shebuti Rayana (CS, Stony Brook University) 28

Deleting maximum element from a Max-heap (cont.) 39 Delete 95 70 83 53 61 72 16 24 48 Does it hold the max-heap property now? NO Shebuti Rayana (CS, Stony Brook University) 29

Deleting maximum element from a Max-heap (cont.) 83 Delete 95 70 39 53 61 72 16 24 48 Does it hold the max-heap property now? NO Shebuti Rayana (CS, Stony Brook University) 30

Deleting maximum element from a Max-heap (cont.) 83 Delete 95 70 72 53 61 39 16 24 48 Does it hold the max-heap property now? YES Shebuti Rayana (CS, Stony Brook University) 31

Deleting maximum element from a Max-heap public int delete(){ } int answer; if (isempty()) throw new Exception(); answer = data[0]; data[0] = data[heapsize 1]; heapsize--; heapify(); return answer; Shebuti Rayana (CS, Stony Brook University) 32

Deleting maximum element from a Max-heap private void heapify() { } int position = 0; int childpos; while (position*2 + 1 < heapsize) { } childpos = position*2 + 1; if (childpos < heapsize-1 && data[childpos+1] > data[childpos]) childpos++; if (data[position]>= data[childpos]) return; swap(position, childpos); position = childpos; Shebuti Rayana (CS, Stony Brook University) 33

Complexity of Heap Assume the heap has N nodes. Then the heap has approximately log 2 N levels. Insert Since the insert swaps at most once per level, the order of complexity of insert is O(log N) Delete Since the delete swaps at most once per level, the order of complexity of delete is also O(log N) Shebuti Rayana (CS, Stony Brook University) 34

Min-heap Can you write the insert and delete methods for min-heap now? Shebuti Rayana (CS, Stony Brook University) 35

Priority Queues A priority queue PQ is like an ordinary queue except that we can only remove the maximum element at any given time (not the front element necessarily). If we use an ordinary array for the PQ, enqueue takes O(1) time but dequeue takes O(n) time. If we use a sorted array for the PQ, enqueue takes O(n) time, while dequeue takes O(1) time. We can use a heap to implement a priority queue, so that enqueue and dequeue take O(log N) time. Shebuti Rayana (CS, Stony Brook University) 36

Priority Queues If we use an ordinary array for the PQ, enqueue takes O(1) time but dequeue takes O(n) time. 0 1 2 3 4 5 6 7 8 25 61 83 95 39 72 48 Insert 48: O(1) PQ size 67 Shebuti Rayana (CS, Stony Brook University) 37

Priority Queues If we use an ordinary array for the PQ, enqueue takes O(1) time but dequeue takes O(n) time. 0 1 2 3 4 5 6 7 8 25 61 83 95 39 72 48 Delete Max (95): O(n) PQ size 7 25 61 83 39 72 48 PQ size 6 Shebuti Rayana (CS, Stony Brook University) 38

Applications of Priority Queue Select print jobs in order of decreasing length Forward packets on routers in order of urgency Select most frequent symbols for compression Sort numbers, picking minimum first Shebuti Rayana (CS, Stony Brook University) 39