CSE 373: Data Structures and Algorithms Lecture 11: Priority Queues (Heaps) 1.

Slides:



Advertisements
Similar presentations
COL 106 Shweta Agrawal and Amit Kumar
Advertisements

Heaps1 Part-D2 Heaps Heaps2 Recall Priority Queue ADT (§ 7.1.3) A priority queue stores a collection of entries Each entry is a pair (key, value)
CMSC 341 Binary Heaps Priority Queues. 8/3/2007 UMBC CSMC 341 PQueue 2 Priority Queues Priority: some property of an object that allows it to be prioritized.
PRIORITY QUEUES AND HEAPS Lecture 19 CS2110 Spring
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture24.
Priority Queues. 2 Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-first-out The “smallest” element.
Priority Queue (Heap) & Heapsort COMP171 Fall 2006 Lecture 11 & 12.
CMPT 225 Priority Queues and Heaps. Priority Queues Items in a priority queue have a priority The priority is usually numerical value Could be lowest.
1 Chapter 6 Priority Queues (Heaps) General ideas of priority queues (Insert & DeleteMin) Efficient implementation of priority queue Uses of priority queues.
Binary Heaps CSE 373 Data Structures Lecture 11. 2/5/03Binary Heaps - Lecture 112 Readings Reading ›Sections
Heaps and heapsort COMP171 Fall Sorting III / Slide 2 Motivating Example 3 jobs have been submitted to a printer in the order A, B, C. Sizes: Job.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on Binary Heaps: enqueue dequeue deleting an.
1 TCSS 342, Winter 2005 Lecture Notes Priority Queues and Heaps Weiss Ch. 21, pp
Priority Queues. Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-first-out –The “smallest” element.
1 CS211, Lecture 20 Priority queues and Heaps Readings: Weiss, sec. 6.9, secs When they've got two queues going, there's never any queue!
Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on Binary Heaps: enqueue dequeue deleting an.
Source: Muangsin / Weiss1 Priority Queue (Heap) A kind of queue Dequeue gets element with the highest priority Priority is based on a comparable value.
Lecture 11 Binary Heap King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
PQ, binary heaps G.Kamberova, Algorithms Priority Queue ADT Binary Heaps Gerda Kamberova Department of Computer Science Hofstra University.
1 Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on Binary Heaps: enqueue dequeue deleting.
CSE 373 Data Structures and Algorithms Lecture 13: Priority Queues (Heaps)
1 CSC 427: Data Structures and Algorithm Analysis Fall 2010 transform & conquer  transform-and-conquer approach  balanced search trees o AVL, 2-3 trees,
CSC 172 DATA STRUCTURES. Priority Queues Model Set with priorities associatedwith elements Priorities are comparable by a < operator Operations Insert.
1 Priority Queues (Heaps)  Sections 6.1 to The Priority Queue ADT  DeleteMin –log N time  Insert –log N time  Other operations –FindMin  Constant.
PRIORITY QUEUES (HEAPS). Queues are a standard mechanism for ordering tasks on a first-come, first-served basis However, some tasks may be more important.
ADT Table and Heap Ellen Walker CPSC 201 Data Structures Hiram College.
The Binary Heap. Binary Heap Looks similar to a binary search tree BUT all the values stored in the subtree rooted at a node are greater than or equal.
Priority Queues and Binary Heaps Chapter Trees Some animals are more equal than others A queue is a FIFO data structure the first element.
Chapter 21 Binary Heap.
data ordered along paths from root to leaf
Chapter 21 Priority Queue: Binary Heap Saurav Karmakar.
1 Heaps and Priority Queues Starring: Min Heap Co-Starring: Max Heap.
CSC 213 – Large Scale Programming Lecture 15: Heap-based Priority Queue.
Priority Queue. Priority Queues Queue (FIFO). Priority queue. Deletion from a priority queue is determined by the element priority. Two kinds of priority.
CSE373: Data Structures & Algorithms Lecture 6: Priority Queues Dan Grossman Fall 2013.
PRIORITY QUEUES AND HEAPS CS16: Introduction to Data Structures & Algorithms Tuesday, February 24,
COSC2007 Data Structures II Chapter 12 Tables & Priority Queues III.
1 Joe Meehean.  We wanted a data structure that gave us... the smallest item then the next smallest then the next and so on…  This ADT is called a priority.
Priority Queues and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
CPSC 252 Binary Heaps Page 1 Binary Heaps A complete binary tree is a binary tree that satisfies the following properties: - every level, except possibly.
PRIORITY QUEUES AND HEAPS Slides of Ken Birman, Cornell University.
CSE373: Data Structures & Algorithms Lecture 6: Priority Queues Kevin Quinn Fall 2015.
Data StructuresData Structures Priority Queue. Recall Queues FIFO:First-In, First-Out Some contexts where this seems right? Some contexts where some things.
Intro. to Data Structures Chapter 6 Priority Queue (Heap) Veera Muangsin, Dept. of Computer Engineering, Chulalongkorn University 1 Priority Queue.
AVL Trees and Heaps. AVL Trees So far balancing the tree was done globally Basically every node was involved in the balance operation Tree balancing can.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
CompSci 100e 8.1 Scoreboard l What else might we want to do with a data structure? AlgorithmInsertionDeletionSearch Unsorted Vector/array Sorted vector/array.
CS 367 Introduction to Data Structures Lecture 8.
Course: Programming II - Abstract Data Types HeapsSlide Number 1 The ADT Heap So far we have seen the following sorting types : 1) Linked List sort by.
Heaps, Heap Sort, and Priority Queues. Background: Binary Trees * Has a root at the topmost level * Each node has zero, one or two children * A node that.
Lecture on Data Structures(Trees). Prepared by, Jesmin Akhter, Lecturer, IIT,JU 2 Properties of Heaps ◈ Heaps are binary trees that are ordered.
CSE373: Data Structures & Algorithms
Heaps (8.3) CSE 2011 Winter May 2018.
Priority Queues and Heaps Suggested reading from Weiss book: Ch. 21
Source: Muangsin / Weiss
Binary Heaps What is a Binary Heap?
Binary Heaps What is a Binary Heap?
Binary Heaps What is a Binary Heap?
ADT Heap data structure
CSE 373: Data Structures and Algorithms
CMSC 341 Lecture 14 Priority Queues & Heaps
CSE 373 Data Structures and Algorithms
CSE 373: Data Structures and Algorithms
A Heap Implementation Chapter 26 Adapted from Pearson Education, Inc.
Priority Queues & Heaps
CSE 373 Priority queue implementation; Intro to heaps
CSC 380: Design and Analysis of Algorithms
Heaps & Multi-way Search Trees
Presentation transcript:

CSE 373: Data Structures and Algorithms Lecture 11: Priority Queues (Heaps) 1

Motivating examples Bandwidth management: A router is connected to a line with limited bandwidth. If there is insufficient bandwidth, the router maintains a queue for incoming data such that the most important data will get forwarded first as bandwidth becomes available. Printing: A shared server has a list of print jobs to print. It wants to print them in chronological order, but each print job also has a priority, and higher-priority jobs always print before lower-priority jobs Algorithms: We are writing a ghost AI algorithm for Pac-Man. It needs to search for the best path to find Pac-Man; it will enqueue all possible paths with priorities (based on guesses about which one will succeed), and try them in order. 2

Priority Queue ADT priority queue: A collection of elements that provides fast access to the minimum (or maximum) element – a mix between a queue and a BST basic priority queue operations: – insert: Add an element to the priority queue (priority matters) – remove (i.e. deleteMin): Removes/returns minimum element 3

Using PriorityQueue s Queue pq = new PriorityQueue (); pq.add("Kona"); pq.add("Daisy"); – implements Queue interface PriorityQueue ( ) constructs a PriorityQueue that orders the elements according to their compareTo (element type must implement Comparable ) add( element ) inserts the element into the PriorityQueue remove() removes and returns the element at the head of the queue peek() returns, but does not remove, the element at the head of the queue 4

Potential Implementations insertdeleteMin Unsorted list (Array) Unsorted list (Linked-List) Sorted list (Array) Sorted list (Linked-List) Binary Search Tree AVL Trees 5

Potential Implementations insertdeleteMin Unsorted list (Array)  (1) (n)(n) Unsorted list (Linked-List)  (1) (n)(n) Sorted list (Array) (n)(n)  (1)* Sorted list (Linked-List) (n)(n)  (1) Binary Search Tree  (n) worst AVL Trees  (log n) 6

Heap properties heap: a tree with the following two properties: – 1. completeness complete tree: every level is full except possibly the lowest level, which must be filled from left to right with no leaves to the right of a missing node (i.e., a node may not have any children until all of its possible siblings exist) Heap shape: 7

Heap properties 2 – 2. heap ordering a tree has heap ordering if P <= X for every element X with parent P in other words, in heaps, parents' element values are always smaller than those of their children implies that minimum element is always the root is every a heap a BST? Are any heaps BSTs? 8

Which are min-heaps? wrong! 9

wrong! Which are max-heaps? 10

Heap height and runtime height of a complete tree is always log n, because it is always balanced – because of this, if we implement a priority queue using a heap, we can provide the O(log n) runtime required for the add and remove operations n-node complete tree of height h: 2 h  n  2 h+1 – 1 h =  log n  11

Implementation of a heap when implementing a complete binary tree, we actually can "cheat" and just use an array – index of root = 1(leave 0 empty for simplicity) – for any node n at index i, index of n.left = 2i index of n.right = 2i + 1 – parent index? 12

Implementing Priority Queue with Binary Heap public interface IntPriorityQueue { public void add(int value); public boolean isEmtpy(); public int peek(); public int remove(); } public class IntBinaryHeap implements IntPriorityQueue { private static final int DEFAULT_CAPACITY = 10; private int[] array; private int size; public IntBinaryHeap () { array = new int[DEFAULT_CAPACITY]; size = 0; }... } 13

Adding to a heap when an element is added to a heap, it should be initially placed as the rightmost leaf (to maintain the completeness property) – heap ordering property becomes broken!

Adding to a heap, cont'd. to restore heap ordering property, the newly added element must be shifted upward ("bubbled up") until it reaches its proper place – bubble up (book: "percolate up") by swapping with parent – how many bubble-ups could be necessary, at most?

Adding to a max-heap same operations, but must bubble up larger values to top 16

Heap practice problem Draw the state of the min-heap tree after adding the following elements to it: 6, 50, 11, 25, 42, 20, 104, 76, 19, 55, 88, 2 17

Code for add method public void add(int value) { // grow array if needed if (size >= array.length - 1) { array = this.resize(); } // place element into heap at bottom size++; int index = size; array[index] = value; bubbleUp(); } 18

The bubbleUp helper private void bubbleUp() { int index = this.size; while (hasParent(index) && (parent(index) > array[index])) { // parent/child are out of order; swap them swap(index, parentIndex(index)); index = parentIndex(index); } // helpers private boolean hasParent(int i) { return i > 1; } private int parentIndex(int i) { return i/2; } private int parent(int i) { return array[parentIndex(i)]; } 19

The peek operation peek on a min-heap is trivial; because of the heap properties, the minimum element is always the root – peek is O(1) – peek on a max-heap would be O(1) as well, but would return you the maximum element and not the minimum one

Code for peek method public int peek() { if (this.isEmpty()) { throw new IllegalStateException(); } return array[1]; } 21