Queues & Priority Queues Radix Sort Heap Sort. Outline n Queues queue operationsqueue operations algorithms with queuesalgorithms with queues radix sortradix.

Slides:



Advertisements
Similar presentations
Data Structures Lecture 13: QUEUES Azhar Maqsood NUST Institute of Information Technology (NIIT)
Advertisements

Michael Alves, Patrick Dugan, Robert Daniels, Carlos Vicuna
PRIORITY QUEUES AND HEAPS Lecture 19 CS2110 Spring
Data Structures and Algorithms (60-254)
ADT Queue 1. What is a Queue? 2. STL Queue 3. Array Implementation of Queue 4. Linked List Implementation of Queue 5. Priority Queue.
ADT Stacks and Queues. Stack: Logical Level “An ordered group of homogeneous items or elements in which items are added and removed from only one end.”
Chapter 7 Queues. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine queue processing Define a queue abstract.
Queues Ellen Walker CPSC 201 Data Structures Hiram College.
Today’s Agenda  Stacks  Queues  Priority Queues CS2336: Computer Science II.
C o n f i d e n t i a l Developed By Nitendra NextHome Subject Name: Data Structure Using C Unit : Overview of Queues.
Event-drive SimulationCS-2303, C-Term Project #3 – Event-driven Simulation CS-2303 System Programming Concepts (Slides include materials from The.
Simulation. Example: A Bank Simulator We are given: –The number of tellers –The arrival time of each customer –The amount of time each customer requires.
1 6.3 Binary Heap - Other Heap Operations There is no way to find any particular key without a linear scan through the entire heap. However, if we know.
Queues and Priority Queues
Chapter 13 Queues and Priority Queues CS Data Structures Mehmet H Gunes Modified from authors’ slides.
© 2006 Pearson Addison-Wesley. All rights reserved8-1 Chapter 8 Queues CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008.
1 Queues Queue Concept Queue Design Considerations Queues in Java Collections APIs Queue Applications Reading L&C , 9.3.
Cmpt-225 Queues. A queue is a data structure that only allows items to be inserted at the end and removed from the front Queues are FIFO (First In First.
CS 206 Introduction to Computer Science II 10 / 26 / 2009 Instructor: Michael Eckmann.
Queues Chapter 8 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
Queues What is a Queue? Queue Implementations: Queue As Array
ADT Stacks and Queues. Stack: Logical Level “An ordered group of homogeneous items or elements in which items are added and removed from only one end.”
Maps A map is an object that maps keys to values Each key can map to at most one value, and a map cannot contain duplicate keys KeyValue Map Examples Dictionaries:
Queues and Priority Queues
Review C++ exception handling mechanism Try-throw-catch block How does it work What is exception specification? What if a exception is not caught?
Chapter 7 Queues. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 7-2 Chapter Objectives Examine queue processing Define a queue abstract.
COMP 121 Week 14: Queues. Objectives Learn how to represent a queue Learn how to use the methods in the Queue interface Understand how to implement the.
90-723: Data Structures and Algorithms for Information Processing Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 5: Stacks and Queues.
CHP-4 QUEUE.
© 2006 Pearson Addison-Wesley. All rights reserved8 A-1 Chapter 8 Queues (slightly modified by Dan Fleck)
Adapted from instructor resources Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights.
Chapter 11 Heap. Overview ● The heap is a special type of binary tree. ● It may be used either as a priority queue or as a tool for sorting.
Data Structures Using C++ 2E Chapter 8 Queues. Data Structures Using C++ 2E2 Objectives Learn about queues Examine various queue operations Learn how.
Data Structures Using Java1 Chapter 7 Queues. Data Structures Using Java2 Chapter Objectives Learn about queues Examine various queue operations Learn.
Graphs. Made up of vertices and arcs Digraph (directed graph) –All arcs have arrows that give direction –You can only traverse the graph in the direction.
Comparison-Based Sorting & Analysis Smt Genap
CS 206 Introduction to Computer Science II 11 / 16 / 2009 Instructor: Michael Eckmann.
1 Simulation Implementation Using high-level languages.
Data Structures Chapter 6. Data Structure A data structure is a representation of data and the operations allowed on that data. Examples: 1.Array 2.Record.
PRIORITY QUEUES AND HEAPS Slides of Ken Birman, Cornell University.
CHP-4 QUEUE. 1.INTRODUCTION  A queue is a linear list in which elements can be added at one end and elements can be removed only at other end.  That.
Binary heaps and Heapsort. Priority Queues n The smallest element is removed item = remove();item = remove(); Priority Queue Minimum.
(c) , University of Washington19a-1 CSC 143 Stacks and Queues: Concepts and Implementations.
1 Algorithms Queues, Stacks and Records stored in Linked Lists or Arrays.
Intro. to Data Structures Chapter 6 Priority Queue (Heap) Veera Muangsin, Dept. of Computer Engineering, Chulalongkorn University 1 Priority Queue.
Chapter 7 Queues Introduction Queue applications Implementations.
Collection types CS Chakrabarti Motivation  Thus far the only collection types we have used are vector and matrix  Problem #1: given an input.
1 Data Structures CSCI 132, Spring 2014 Lecture 7 Queues.
 In general, Queue is line of person waiting for their turn at some service counter like ticket window at cinema hall, at bus stand or at railway station.
© Oxford University Press All rights reserved. Data Structures Using C, 2e Reema Thareja.
Review Array Array Elements Accessing array elements
Data Structures Using C++ 2E
CSE373: Data Structures & Algorithms
Data Structures Using C, 2e
Queues.
Queues Chapter 4.
COSC160: Data Structures: Lists and Queues
Queues Queue Concept Queue Design Considerations
Lectures Queues Chapter 8 of textbook 1. Concepts of queue
Stacks and Queues.
Hashing Exercises.
Chapter 13 Queues and Priority Queues
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
CSC 143 Queues [Chapter 7].
Queues.
Stack A data structure in which elements are inserted and removed only at one end (called the top). Enforces Last-In-First-Out (LIFO) Uses of Stacks Evaluating.
QUEUE Visit for more Learning Resources Free Powerpoint Templates.
Priority Queues Chapters 10 & 26.
CSCS-200 Data Structure and Algorithms
DATA STRUCTURES IN PYTHON
Presentation transcript:

Queues & Priority Queues Radix Sort Heap Sort

Outline n Queues queue operationsqueue operations algorithms with queuesalgorithms with queues radix sortradix sort n Priority Queues priority queue operationspriority queue operations the “heap” data structurethe “heap” data structure heap sortheap sort

Queue Operations n Queues require these operations add at back (enqueue, put, insert).add(item)add at back (enqueue, put, insert).add(item) delete from front (dequeue, get).remove()delete from front (dequeue, get).remove() n Typically have some others check if empty.isEmpty()check if empty.isEmpty() inspect front element (getFront, peek).front()inspect front element (getFront, peek).front() empty it out.clear()empty it out.clear() get size.size()get size.size()

A Queue n Arranged left to right front at the leftfront at the left n Old items are removed or dequeued at front myQueue.remove()myQueue.remove() n New items are inserted or enqueued at back myQueue.add(99)myQueue.add(99) Queue Front Back

A Queue n Arranged left to right front at the leftfront at the left n Old items are removed or dequeued at front myQueue.remove()myQueue.remove() n New items are inserted or enqueued at back myQueue.add(99)myQueue.add(99) Queue Front Back

A Queue n Arranged left to right front at the leftfront at the left n Old items are removed or dequeued at front myQueue.remove()myQueue.remove() n New items are inserted or enqueued at back myQueue.add(99)myQueue.add(99) Queue Front Back

Real World Queues n Any line-up bank, ticket window, amusement ridebank, ticket window, amusement ride (except – people might give up & leave)(except – people might give up & leave) n Assembly line chassis inserted at one endchassis inserted at one end completed vehicle comes off the othercompleted vehicle comes off the other

FILO and LILO n Stack operations all at one end n Last element in the stack is the first one out Last In, First Out = LIFOLast In, First Out = LIFO AKA FILO = First In, Last OutAKA FILO = First In, Last Out n Last element in a queue is last one out Last In, Last Out = LILOLast In, Last Out = LILO AKA FIFO = First In, First OutAKA FIFO = First In, First Out

Exercise n Draw the queues that result from the following operations n Start with empty each time add A, add B, add C, remove, removeadd A, add B, add C, remove, remove add 1, add 2, remove, add 3, add 4add 1, add 2, remove, add 3, add 4

Exceptional Circumstances n Similar to stacks: try to remove/get front of empty queuetry to remove/get front of empty queue try to add to a full queuetry to add to a full queue try to add a nulltry to add a null n Solutions similar as well: return null / throw an exceptionreturn null / throw an exception return false / throw an exceptionreturn false / throw an exception two versions of remove and fronttwo versions of remove and front

Using Queues n File server n Railway sidings n Wire routing (shortest path) n Image component labeling n Radix Sort

Wire Routing Problem n Need to connect two locations on a device can’t go over existing componentscan’t go over existing components want shortest pathwant shortest path S1F

Wire Routing Problem n Represent device by 0-1 matrix 0 = free space0 = free space 1 = component1 = component n Need start & end points locations in matrixlocations in matrix (2, 8) and (2, 10)(2, 8) and (2, 10)

Wire Routing Problem n Two Pass Method to RouteWire(matrix, start, end) // find distances from start LabelDistances(matrix, start, end) // find path from end back to start FindRouteBack(matrix, start, end)

Distance Pass n add start cell, labeled 2 [(2, 8)][(2, 8)] n remove start cell (=2), add its neighbours, labeled 3 [(1, 8), (3, 8), (2, 7)][(1, 8), (3, 8), (2, 7)] n remove next cell (=3), add its neighbours, labeled 4 [(3, 8), (2, 7), (0, 8), (1, 7)][(3, 8), (2, 7), (0, 8), (1, 7)] s1e e ab a a e e

Distance Pass n Repeat until you reach goal or until queue is emptyor until queue is empty n Remove (3, 10), labeled 5, label its neighbours 6 [(4, 7), (2, 5), (0, 10), …][(4, 7), (2, 5), (0, 10), …] add (2, 10) = endadd (2, 10) = end can stop nowcan stop now ab a a

Label Distances Code to LabelDistances(matrix, start, end) matrix[start]  2; q.add(start); while (!q.empty()) if (q.front() = end)break; LabelNeighbours(q.top(), matrix); q.remove(); if (q.empty()) throw exception(“No path found”); Doesn’t stop as early as it could

Path Finding n Start at goal n Pick a neighbour labeled one less than you n Repeat until reach start in this example a single pathin this example a single path

Finding Path Back to FindRouteBack(matrix, start, end) current  end; while (current != start) label  matrix[current]; matrix[current]  1;// now used current  FindNeighbour(matrix, current, label–1); matrix[start]  1;// start used, too

Exercises n Show how the queue develops for the rest of the example above assume always look north, east, south, westassume always look north, east, south, west assume stop as soon as the end cell labeledassume stop as soon as the end cell labeled n To think about how could we rewrite the code above to stop as soon as the end cell gets labeled?how could we rewrite the code above to stop as soon as the end cell gets labeled?

Radix Sort n An array of numbers to sort [75, 73, 72, 64, 115, 31, 232, 105][75, 73, 72, 64, 115, 31, 232, 105] n A List of 10 queues List > radix = …;

Radix Sort n Use 1s digit to choose queue to put them in [75, 73, 72, 64, 115, 31, 232, 105][75, 73, 72, 64, 115, 31, 232, 105] n A List of 10 queues List > radix = …;

Radix Sort n Recombine in order from 0 to 9 [31, 72, 232, 73, 64, 75, 115, 105][31, 72, 232, 73, 64, 75, 115, 105] n A List of 10 queues List > radix = …;

Radix Sort n Repeat using 10s digit [31, 72, 232, 73, 64, 75, 115, 105][31, 72, 232, 73, 64, 75, 115, 105] n A List of 10 queues List > radix = …;

Radix Sort n Recombine in order from 0 to 9 [105, 115, 31, 232, 64, 72, 73, 75][105, 115, 31, 232, 64, 72, 73, 75] n A List of 10 queues List > radix = …;

Radix Sort n Repeat using 100s digit [105, 115, 31, 232, 64, 72, 73, 75][105, 115, 31, 232, 64, 72, 73, 75] n A List of 10 queues List > radix = …;

Radix Sort n Recombine in order from 0 to 9 [31, 64, 72, 73, 75, 105, 115, 232][31, 64, 72, 73, 75, 105, 115, 232] n A List of 10 queues List > radix = …;

Radix Sort n Quit when no number has the digit you’re looking for find maximum & go until it has been passedfind maximum & go until it has been passed for (r = 1; max <= r; r *= 10) { splitList(arr, radix, r);// arr  radix recombine(arr, radix);// radix  arr }

Complexity of Radix Sort n Number of operations: split queue: linear in list lengthsplit queue: linear in list length recombine queues: linear in list lengthrecombine queues: linear in list length how many times do we split/recombine?how many times do we split/recombine? »doesn’t depend on length of the list n Linear in length of list looks better than quadratic or N log Nlooks better than quadratic or N log N »but not necessarily better….

Problems for Radix Sort n Depends on “length” of biggest item 6-digit numbers take twice as long to sort as 3- digit numbers6-digit numbers take twice as long to sort as 3- digit numbers 80-character strings take ten times as long to sort as 8-character strings80-character strings take ten times as long to sort as 8-character strings »and need 94 or more queues n Doesn’t work on numbers with decimals »unless write them into long Strings and then read them back again afterwards

Priority Queue Operations n Priority queues must have these operations: add (push, insert).add(item)add (push, insert).add(item) remove highest priority item (pop).remove()remove highest priority item (pop).remove() n Typically have more operations…. check if empty.isEmpty()check if empty.isEmpty() look at highest priority item.peek()look at highest priority item.peek() get size.size()get size.size() make empty.clear()make empty.clear()

Priority Queues n Priority queue is a queue where the “most important” items get removed first “most important” = “highest priority”“most important” = “highest priority” n Most important is usually the smallest priority #1priority #1 priority #2priority #2 … priority # 1,000,004priority # 1,000,004

Priority Queues n The smallest element is removed pq.remove();pq.remove();

Priority Queues n Additions made anywhere convenient pq.add(75);pq.add(75); n New items will move up as required! pq.add(10)pq.add(10)

Priority Queues n Each element in the queue has a priority in our examples that’s all they havein our examples that’s all they have in some app.s may have other informationin some app.s may have other information n Ties can be broken in any manner at all (!) may be FIFO, but not necessarilymay be FIFO, but not necessarily n Can think of it as a sorted list but that’s not actually what we’re going to do!but that’s not actually what we’re going to do!

Real World Priority Queues n Printer queue n Time-sharing job queue n Airport baggage check with separate “Executive Class” check-in

PQ Applications n Asynchronous event simulation n Sort a list

Asynchronous Events n Simulation of timed events n Event record event type + time it occursevent type + time it occurs n Keep events in a PQ get next event from the PQ (minimum element)get next event from the PQ (minimum element) update the clock with the timeupdate the clock with the time generate any new events & insert into the PQgenerate any new events & insert into the PQ

Bank Simulation n Customers arrive at random served in the order they arriveserved in the order they arrive »(they queue!) n Multiple tellers available serve customers as they become availableserve customers as they become available some customers take more time than otherssome customers take more time than others n Simulate with randomness random arrival times, random service timesrandom arrival times, random service times

Bank Simulation Events n Customers arrive at random serve in order of arrivalserve in order of arrival event arrival: record time of arrivalevent arrival: record time of arrival n Customers served by first available teller service takes random amount of timeservice takes random amount of time event departure: record time service will endevent departure: record time service will end n Handle events in the order they happen priority queue sorted on time of eventpriority queue sorted on time of event

Bank Simulation Parameters n New arrival every 1 to 10 minutes for an hourfor an hour can schedule these at start of simulationcan schedule these at start of simulation n Each service takes 1 to 10 minutes can’t schedule until after they go to the teller!can’t schedule until after they go to the teller! events need to be added during the simulationevents need to be added during the simulation n Calculate average & maximum wait time

Arrival Schedule eventPQ arrival(4), arrival(7), arrival(8), arrival(17), … lineUpQ time 0 numTellersFree 2 customers 0 totalWaitingTime 0 maxWaitingTime 0

arrival(4), arrival(7), arrival(8), arrival(17), … First Event: time = 4 eventPQ arrival(7), arrival(8), arrival(17), arrival(18), … lineUpQ time 4 numTellersFree 2 customers 0 totalWaitingTime 0 maxWaitingTime 0 arrival(7), arrival(8), departure(10), arrival(17), … 1 1

Next Event: 7 eventPQ arrival(8), departure(10), arrival(17), arrival(18), … lineUpQ time 7 numTellersFree 1 customers 1 totalWaitingTime 0 maxWaitingTime 0 arrival(8), departure(10), departure(11), … 0 2

Next Event: 8 eventPQ departure(10), departure(11), arrival(17), … lineUpQ time 8 numTellersFree 0 customers 2 totalWaitingTime 0 maxWaitingTime 0 arrival(8)

departure(10), departure(11), arrival(17), … Next Event: 10 eventPQ departure(11), arrival(17), arrival(18), … lineUpQ arrival(8) time 10 numTellersFree 0 customers 2 totalWaitingTime 0 maxWaitingTime 0 departure(11), arrival(17), departure(17), … 0 322

General Event Simulation n P.Q. of events some events added at startsome events added at start some events added as go alongsome events added as go along loop until P.Q. is emptyloop until P.Q. is emptyaddStartingEvents(pq); while (!pq.isEmpty()) { Event e = pq.remove(); Event e = pq.remove(); processEvent(e, pq); processEvent(e, pq);}

Sorting with a P.Q. n Add all items from array into P.Q. for (int i = 0; i < a.length; ++i) { pq.add(a[i]); pq.add(a[i]);} n Remove them in order back into the array for (int i = 0; i < a.length; ++i) { a[i] = pq.remove(); a[i] = pq.remove();} n That’s almost heap sort

Questions n Next time: reviewreview