CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims. Lecture 17: Heaps and Priority Queues

Similar documents
PRIORITY QUEUES AND HEAPS. Lecture 19 CS2110 Spring 2014

PRIORITY QUEUES AND HEAPS. Slides of Ken Birman, Cornell University

PRIORITY QUEUES AND HEAPS

RBT Operations. The basic algorithm for inserting a node into an RBT is:

CSS 343 Data Structures, Algorithms, and Discrete Math II. Balanced Search Trees. Yusuf Pisan

CSE 100: RED-BLACK TREES

Chapter 7: Sorting 7.1. Original

CSI33 Data Structures

Programming Abstractions

5 AVL trees: deletion

MITOCW 6. AVL Trees, AVL Sort

COS 226 Algorithms and Data Structures Fall Midterm Exam

COS 226 Algorithms and Data Structures Fall Midterm Exam

Self-Adjusting Binary Search Trees. Andrei Pârvu

CS : Data Structures

Link State Routing. Brad Karp UCL Computer Science. CS 3035/GZ01 3 rd December 2013

Binary trees. Application: AVL trees and the golden ratio. The golden ratio. φ 1=1/φ 1. φ =1+

Topic 23 Red Black Trees

4.4 Shortest Paths in a Graph Revisited

Binary Search Tree (Part 2 The AVL-tree)

1 Permutations. Example 1. Lecture #2 Sept 26, Chris Piech CS 109 Combinatorics

Balanced Trees. Balanced Trees Tree. 2-3 Tree. 2 Node. Binary search trees are not guaranteed to be balanced given random inserts and deletes

MITOCW R11. Principles of Algorithm Design

Introduction to. Algorithms. Lecture 10. Prof. Constantinos Daskalakis CLRS

Past questions from the last 6 years of exams for programming 101 with answers.

mywbut.com Two agent games : alpha beta pruning

Huffman Coding - A Greedy Algorithm. Slides based on Kevin Wayne / Pearson-Addison Wesley

Diffracting Trees and Layout

Link State Routing. Stefano Vissicchio UCL Computer Science CS 3035/GZ01

Homework Assignment #1

DATA STRUCTURE TREES UNIT II

Introduction to. Algorithms. Lecture 10. Prof. Piotr Indyk

Permutations. Example 1. Lecture Notes #2 June 28, Will Monroe CS 109 Combinatorics

CS 540-2: Introduction to Artificial Intelligence Homework Assignment #2. Assigned: Monday, February 6 Due: Saturday, February 18

1 Permutations. 1.1 Example 1. Lisa Yan CS 109 Combinatorics. Lecture Notes #2 June 27, 2018

MITOCW ocw lec11

Grading Delays. We don t have permission to grade you (yet) We re working with tstaff on a solution We ll get grades back to you as soon as we can

arxiv: v1 [math.co] 7 Aug 2012

Game Theory and Randomized Algorithms

and 6.855J. Network Simplex Animations

Module 3 Greedy Strategy

AIMA 3.5. Smarter Search. David Cline

Informatica Universiteit van Amsterdam. Performance optimization of Rush Hour board generation. Jelle van Dijk. June 8, Bachelor Informatica

UNIVERSITY of PENNSYLVANIA CIS 391/521: Fundamentals of AI Midterm 1, Spring 2010

From Shared Memory to Message Passing

CS188 Spring 2014 Section 3: Games

ARTIFICIAL INTELLIGENCE (CS 370D)

Transportation Timetabling

A Memory Efficient Anti-Collision Protocol to Identify Memoryless RFID Tags

Lecture 20 November 13, 2014

COMP Online Algorithms. Paging and k-server Problem. Shahin Kamali. Lecture 11 - Oct. 11, 2018 University of Manitoba

Generalized Game Trees

Computer Graphics (CS/ECE 545) Lecture 7: Morphology (Part 2) & Regions in Binary Images (Part 1)

16.410/413 Principles of Autonomy and Decision Making

A Note on Downup Permutations and Increasing Trees DAVID CALLAN. Department of Statistics. Medical Science Center University Ave

The Theory Behind the z/architecture Sort Assist Instructions

Real Time Operating Systems Lecture 29.1

Announcements. Homework 1 solutions posted. Test in 2 weeks (27 th ) -Covers up to and including HW2 (informed search)

CS445: Modeling Complex Systems

Games and Adversarial Search II

Homework Assignment #2

AC : MOTIVATING STUDENTS TO LEARN PROGRAMMING USING GAME ASSIGNMENTS

Examination paper for TDT4120 Algorithms and Data Structures

APCS Study Guide Part I (Free Response)

Module 3 Greedy Strategy

On Burst Transmission Scheduling in Mobile TV Broadcast Networks

CSE 332: Data Structures and Parallelism Games, Minimax, and Alpha-Beta Pruning. Playing Games. X s Turn. O s Turn. X s Turn.

The Complexity of Sorting with Networks of Stacks and Queues

HEAPABLE SEQUENCES AND SUBSEQUENCES

Multitree Decoding and Multitree-Aided LDPC Decoding

Outline. EEC-484/584 Computer Networks. Homework #1. Homework #1. Lecture 8. Wenbing Zhao Homework #1 Review

Merge Sort. Note that the recursion bottoms out when the subarray has just one element, so that it is trivially sorted.

Search then involves moving from state-to-state in the problem space to find a goal (or to terminate without finding a goal).

Machine Translation - Decoding

Heapable Sequences and Subseqeuences

(Lec19) Geometric Data Structures for Layouts

Multiplayer Pushdown Games. Anil Seth IIT Kanpur

Abstract. 1 Introduction

Skip Lists S 3 S 2 S 1. 2/6/2016 7:04 AM Skip Lists 1

Lectures: Feb 27 + Mar 1 + Mar 3, 2017

MITOCW 7. Counting Sort, Radix Sort, Lower Bounds for Sorting

Minimax Trees: Utility Evaluation, Tree Evaluation, Pruning

DVA325 Formal Languages, Automata and Models of Computation (FABER)

CS/COE 1501

The power behind an intelligent system is knowledge.

Universal Cycles for Permutations Theory and Applications

Compiler Optimisation

M14/4/COMSC/HP1/ENG/TZ0/XX. Computer science. Paper 1. Friday 16 May 2014 (afternoon) 2 hours 10 minutes INSTRUCTIONS TO CANDIDATES

Design of Parallel Algorithms. Communication Algorithms

Contents. Basic Concepts. Histogram of CPU-burst Times. Diagram of Process State CHAPTER 5 CPU SCHEDULING. Alternating Sequence of CPU And I/O Bursts

Notes for Recitation 3

Global State and Gossip

Adversary Search. Ref: Chapter 5

Intelligent Agents & Search Problem Formulation. AIMA, Chapters 2,

(CSC-3501) Lecture 6 (31 Jan 2008) Seung-Jong Park (Jay) CSC S.J. Park. Announcement

CS188 Spring 2010 Section 3: Game Trees

Lecture 7. Review Blind search Chess & search. CS-424 Gregory Dudek

Robonet - MANET for Robot Communication

CSE 100: BST AVERAGE CASE AND HUFFMAN CODES

Pin-Permutations and Structure in Permutation Classes

Transcription:

CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims Lecture 17: Heaps and Priority Queues

Stacks and Queues as Lists Stack (LIFO) implemented as list insert (i.e. push) to, extract (i.e. pop) from front of list Queue (FIFO) implemented as list insert (i.e. add) on back of list, extract (i.e. poll) from front of list All operations are O(1) first last 55 120 19 1

Priority Queue ADT Definition data items are Comparable lesser elements (as determined by compareto()) have higher priority extract() returns the element with the highest priority i.e. least in the compareto() ordering break ties arbitrarily alternatively could break ties FIFO, but lets keep it simple

Priority Queue Examples Scheduling jobs to run on a computer default priority = arrival time priority can be changed by operator Scheduling events to be processed by an event handler priority = time of occurrence Airline check-in first class, business class, coach FIFO within each class

java.util.priorityqueue<e> boolean add(e e) {...} //insert an element (insert) void clear() {...} //remove all elements E peek() {...} //return min element without removing //(null if empty) E poll() {...} //remove min element (extract) //(null if empty) int size() {...}

Priority Queues as Lists Maintain as unordered list (i.e. queue) insert() puts new element at front O(1) extract() must search the list O(n) Maintain as ordered list insert() must search the list O(n) extract() gets element at front O(1) In either case, O(n 2 ) to process n elements Can we do better?

Important Special Case Fixed (and small) number of p priority levels Queue within each level Example: airline check-in insert() insert in appropriate queue O(1) extract() must find a nonempty queue O(p)

Heaps A heap is a concrete data structure that can be used to implement priority queues Gives better complexity than either ordered or unordered list implementation: insert(): O(log n) extract(): O(log n) O(n log n) to process n elements NOTE: Do not confuse with heap memory, where the Java virtual machine allocates space for objects different usage of the word heap

Heap Invariant Binary tree with data at each node Satisfies the Heap Order Invariant: The least (highest priority) element of any subtree is found at the root of that subtree.

Least element in any subtree is always found at the root of that subtree 4 14 21 8 19 35 22 38 55 10 20 But it is possible to have smaller elements deeper in the tree!

Examples of Heaps Ages of people in family tree parent is always older than children, but you can have an uncle who is younger than you Salaries of employees of a company bosses generally make more than subordinates, but a VP in one subdivision may make less than a Project Supervisor in a different subdivision

Balanced Heaps Two restrictions: Any node of depth < d 1 has exactly 2 children, where d is the height of the tree implies that any two maximal paths (path from a root to a leaf) are of length d or d 1, and the tree has at least 2d nodes All maximal paths of length d are to the left of those of length d 1

A Balanced Heap 4 14 21 8 19 35 22 38 55 10 20 d = 3

Store in an ArrayList Elements of the heap are stored in the array in order, going across each level from left to right, top to bottom The children of the node at array index n are found at 2n + 1 and 2n + 2 The parent of node n is found at (n 1)/2

Store in an ArrayList 4 0 1 2 14 3 4 5 21 8 19 35 7 8 9 10 11 22 38 55 10 20 children of node n are found at 2n + 1 and 2n + 2

insert() Put the new element at the end of the array If this violates heap order because it is smaller than its parent, swap it with its parent Continue swapping it up until it finds its rightful place The heap invariant is maintained!

insert() Example 4 14 21 8 19 35 22 38 55 10 20

insert() Example 4 14 21 8 19 35 22 38 55 10 20 5

insert() Example 4 14 21 8 5 35 22 38 55 10 20 19

insert() Example 4 5 21 8 14 35 22 38 55 10 20 19

insert() Example 4 5 21 8 14 35 22 38 55 10 20 19

insert() Example 4 5 21 8 14 35 22 38 55 10 20 19 2

insert() Example 4 5 21 8 14 2 22 38 55 10 20 19 35

insert() Example 4 2 21 8 14 5 22 38 55 10 20 19 35

insert() Example 2 4 21 8 14 5 22 38 55 10 20 19 35

insert() Example 2 4 21 8 14 5 22 38 55 10 20 19 35

Analysis of insert() Time is O(log n), since the tree is balanced At most log(d) swaps up the tree before invariant is restored size of tree is exponential as a function of depth d depth of tree is logarithmic as a function of size n Each insertion is finished after at most d <= log(n) swaps

extract() Remove the least element it is at the root This leaves a hole at the root fill it in with the last element of the array If this violates heap order because the root element is too big, swap it down with the smaller of its children Continue swapping it down until it finds its rightful place The heap invariant is maintained!

extract() Example 4 5 21 8 14 35 22 38 55 10 20 19

extract() Example 4 5 21 8 14 35 22 38 55 10 20 19

extract() Example 4 5 21 8 14 35 22 38 55 10 20 19

extract() Example 4 19 5 21 8 14 35 22 38 55 10 20

extract() Example 4 5 19 21 8 14 35 22 38 55 10 20

extract() Example 4 5 14 21 8 19 35 22 38 55 10 20

extract() Example 4 5 14 21 8 19 35 22 38 55 10 20

extract() Example 4 5 14 21 8 19 35 22 38 55 10 20

extract() Example 4 5 14 21 8 19 35 22 38 55 10 20

extract() Example 4 5 20 14 21 8 19 35 22 38 55 10

extract() Example 4 5 20 14 21 8 19 35 22 38 55 10

extract() Example 4 5 8 14 21 20 19 35 22 38 55 10

extract() Example 4 5 8 14 21 10 19 35 22 38 55 20

extract() Example 4 5 8 14 21 10 19 35 22 38 55 20

Analysis of extract() Time is O(log n), since the tree is balanced At most log(d) swaps down towards the leaves of the tree before invariant is restored size of tree is exponential as a function of depth d depth of tree is logarithmic as a function of size n Each extraction is finished after at most d <= log(n) swaps

HeapSort Given a Comparable[] array of length n Put all n elements into a heap O(n log n) Repeatedly get the min and sequentially put into new array O(n log n)