Queues. Queue Definition Ordered list with property: All insertions take place at one end (tail) All insertions take place at one end (tail) All deletions.

Slides:



Advertisements
Similar presentations
Queues Printer queues Several jobs submitted to printer Jobs form a queue Jobs processed in same order as they were received.
Advertisements

Stacks, Queues, and Linked Lists
Linear Lists – Array Representation
Chapter 3 – Lists A list is just what the name implies, a finite, ordered sequence of items. Order indicates each item has a position. A list of size 0.
Queue Definition Ordered list with property: –All insertions take place at one end (tail) –All deletions take place at other end (head) Queue: Q = (a 0,
Queues. Queue Definition Ordered list with property: All insertions take place at one end (tail) All insertions take place at one end (tail) All deletions.
Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can be instantiated.
Data Structures Lecture 13: QUEUES Azhar Maqsood NUST Institute of Information Technology (NIIT)
Queues A waiting line that grows by adding elements to its end and shrinks by taking elements from its front Line at the grocery store Cars in traffic.
The Queue ADT Definition A queue is a restricted list, where all additions occur at one end, the rear, and all removals occur at the other end, the front.
Data Structure (Part I) Stacks and Queues. Introduction to Stack An stack is a ordered list in which insertion and deletions are made at one end. –The.
Introduction to C Programming CE Lecture 12 Circular Queue and Priority Queue Data Structures.
1 Queues – Chapter 3 A queue is a data structure in which all additions are made at one end called the rear of the queue and all deletions are made from.
E.G.M. Petrakislists, stacks, queues1 Stacks Stack: restricted variant of list –Elements may by inserted or deleted from only one end  LIFO lists –Top:
Queues CS-212 Dick Steflik. Queues First In, First Out operation – FIFO As items are added they are chronologically ordered, items are removed in their.
ADT Queue 1. What is a Queue? 2. STL Queue 3. Array Implementation of Queue 4. Linked List Implementation of Queue 5. Priority Queue.
LINKED QUEUES P LINKED QUEUE OBJECT Introduction Introduction again, the problem with the previous example of queues is that we are working.
Queues 4/14/2017 5:24 PM 5.2 Queues Queues Dr Zeinab Eid.
1 Queues (5.2) CSE 2011 Winter May Announcements York Programming Contest Link also available from.
Data Structure Dr. Mohamed Khafagy.
Queue Overview Queue ADT Basic operations of queue
Today’s Agenda  Stacks  Queues  Priority Queues CS2336: Computer Science II.
Chapter 7 Queues. © 2005 Pearson Addison-Wesley. All rights reserved7-2 The Abstract Data Type Queue A queue –New items enter at the back, or rear, of.
Sorting Algorithms. Motivation Example: Phone Book Searching Example: Phone Book Searching If the phone book was in random order, we would probably never.
1 Chapter 6 Priority Queues (Heaps) General ideas of priority queues (Insert & DeleteMin) Efficient implementation of priority queue Uses of priority queues.
Stacks and Queues COMP171 Fall Stack and Queue / Slide 2 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations.
Main Index Contents 11 Main Index Contents Model for a Queue Model for a Queue The Queue The Queue ADTQueue ADT (3 slides) Queue ADT Radix Sort Radix Sort.
Chapter 3. Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can be.
Queues.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
CS 206 Introduction to Computer Science II 10 / 26 / 2009 Instructor: Michael Eckmann.
Queues CS-240 & CS-341 Dick Steflik. Queues First In, First Out operation – FIFO As items are added they are chronologically ordered, items are removed.
CS 1031 Queues Definition of a Queue Examples of Queues Design of a Queue Class Different Implementations of the Queue Class.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
Information and Computer Sciences University of Hawaii, Manoa
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
Data Structures (part 2). Stacks An Everyday Example Your boss keeps bringing you important items to deal with and keeps saying: “Put that last ‘rush’
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 7: Queues Data Abstraction & Problem Solving with C++
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Linked List (Part I). Introduction  Weakness of storing an ordered list in array: Insertion and deletion of arbitrary elements are expensive. ○ Example:
Computer Science Department Data Structures and Algorithms Queues Lecture 5.
UNIT II Queue. Syllabus Contents Concept of queue as ADT Implementation using linked and sequential organization. – linear – circular queue Concept –
FALL 2005CENG 213 Data Structures1 Priority Queues (Heaps) Reference: Chapter 7.
Chapter 7 Queues Introduction Queue applications Implementations.
2005MEE Software Engineering Lecture 7 –Stacks, Queues.
Chap 3 Stack and Queue. Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable.
Queues Another Linear ADT Copyright © 2009 Curt Hill.
Queues CS 367 – Introduction to Data Structures. Queue A queue is a data structure that stores data in such a way that the last piece of data stored,
 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.
1 Priority Queues (Heaps). 2 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full sorted.
Review Array Array Elements Accessing array elements
Unit-3 Queues-operations, array and linked representations. Circular Queue operations, Dequeues, applications of queue.
CS505 Data Structures and Algorithms
UNIT II Queue.
Stack and Queue APURBO DATTA.
Stacks Stack: restricted variant of list
CMSC 341 Lecture 5 Stacks, Queues
Chapter 16-2 Linked Structures
Linked List (Part I) Data structure.
CSC 143 Queues [Chapter 7].
Queues: Implemented using Arrays
Stacks.
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
Queues Jyh-Shing Roger Jang (張智星)
Circular Queues: Implemented using Arrays
Queues Definition of a Queue Examples of Queues
Queues: Implemented using Linked Lists
Getting queues right … finally (?)
The Queue ADT Definition A queue is a restricted list, where all additions occur at one end, the rear, and all removals occur at the other end, the front.
Presentation transcript:

Queues

Queue Definition Ordered list with property: All insertions take place at one end (tail) All insertions take place at one end (tail) All deletions take place at other end (head) All deletions take place at other end (head) Queue: Q = (a 0, a 1, …, a n-1 ) a0 is the front element, a n-1 is the tail, and a i is behind a i-1 for all i, 1 <= i < n

Queue Definition Because of insertion and deletion properties, Queue is very similar to: Line at the grocery store Cars in traffic Network packets …. Also called first-in first out lists

Queue Implementation Ideas Container type class for holding data Array versus Linked List? Who’s better? Head index pointer Position right before first element in queue Tail index pointer Position of last element in queue

Array-Based Queue Definition template template class Queue {public: Queue(int MaxQueueSize = DefaultSize); ~Queue(); bool IsFull(); bool IsFull(); bool IsEmpty(); void Add(const KeyType& item); KeyType* Delete(KeyType& item); private: void QueueFull(); // error handling void QueueEmpty();// error handling int head, tail; KeyType* queue; int MaxSize; };

Queue Implementation Constructor: template template Queue ::Queue(int MaxQueueSize): MaxSize(MaxQueueSize) { queue = new KeyType[MaxSize]; head = tail = -1; }

Queue Implementation Destructor: template template Queue<KeyType>::~Queue(){ delete [] queue; head = tail = -1; }

Queue Implementation IsFull() and IsEmpty(): template template bool Queue ::IsFull() { return (tail == (MaxSize-1)); } template template bool Queue ::IsEmpty() { return (head == tail); }

Queue Implementation Add() and Delete(): template template void Queue ::Add (const KeyType& item) { if (IsFull()) {QueueFull(); return;} else { tail = tail + 1; queue[tail] = item; } } template template KeyType* Queue ::Delete(KeyType& item) { if (IsEmpty()) {QueueEmpty(); return 0}; else { head = head + 1; item = queue[head]; return &item; } }

Example: Job Scheduling OS has to manage how jobs (programs) are executed on the processor – 2 typical techniques: -Priority based: Some ordering over of jobs based on importance (Professor X’s jobs should be allowed to run first over Professor Y). -Queue based: Equal priority, schedule in first in first out order.

Queue Based Job Processing FrontRear Q[0] Q[1] Q[2] Q[3] CommentsInitial0 J1 J1 Job 1 Enters 1 J1 J2 J1 J2 Job 2 Enters 2 J1 J2 J3 J1 J2 J3 Job 3 Enters 02 J2 J3 J2 J3 Job 1 Leaves 03 J2 J3 J4 J2 J3 J4 Job 4 Enters 13 J3 J4 J3 J4 Job 2 Leaves MaxSize = 4

Job Processing When J4 enters the queue, rear is updated to 3. When J4 enters the queue, rear is updated to 3. When rear is 3 in a 4-entry queue, run out of space. When rear is 3 in a 4-entry queue, run out of space. The array may not really be full though, if head is not The array may not really be full though, if head is not Head can be > -1 if items have been removed from queue. Head can be > -1 if items have been removed from queue. Possible Solution: When rear = (maxSize – 1) attempt to shift data forwards into empty spaces and then do Add.

Queue Shift private void shiftQueue(KeyType* queue, int & head, int & tail) { int difference = head – (-1); // head + 1 for (int j = head + 1; j < maxSize; j++) { queue[j-difference] = queue[j]; } head = -1; tail = tail – difference; }

Queue Shift Worst Case For Queue Shift: Full Queue Alternating Delete and Add statements FrontRear Q[0] Q[1] Q[2] Q[3] Comments3 J1 J2 J3 J4 J1 J2 J3 J4Initial 03 J2 J3 J4 J2 J3 J4 Job 1 Leaves 3 J2 J3 J4 J5 J2 J3 J4 J5 Job 5 Enters 03 J3 J4 J5 J3 J4 J5 Job 2 Enters 3 J3 J4 J5 J6 J3 J4 J5 J6 Job 6 Leaves

Worst Case Queue Shift Worst Case: Worst Case: Shift entire queue: Cost of O(n) Shift entire queue: Cost of O(n) Do every time perform an add Do every time perform an add Too expensive to be useful Too expensive to be useful Worst case is not that unlikely, so this suggests finding an alternative implementation.

Circular Array Implementation Basic Idea: Allow the queue to wrap-around Implement with addition mod size: tail = (tail + 1) % queueSize; N-1 N-2 J1 J2 J3 J N-1 N-2 J2 J3 J1

Linked Queues Problems with implementing queues on top of arrays Problems with implementing queues on top of arrays Sizing problems (bounds, clumsy resizing, …) Sizing problems (bounds, clumsy resizing, …) Non-circular Array – Data movement problem Non-circular Array – Data movement problem Now that have the concepts of list nodes, can take advantage of to represent queues. Now that have the concepts of list nodes, can take advantage of to represent queues. Need to determine appropriate way of: Need to determine appropriate way of: Representing front and rear Representing front and rear Facilitating node addition and deletion at the ends. Facilitating node addition and deletion at the ends.

Linked Queues CAT Front Rear MATHAT FrontRear Add(Hat) Add(Mat) Add(Cat)Delete()

Linked Queues Class QueueNode{ friend class Queue; public: QueueNode(int d, QueueNode * l); private: int data; QueueNode *link; };

Linked Queues class Queue {public:Queue();~Queue(); void Add(const int); int* Delete(int&); bool isEmpty(); private: QueueNode* front; QueueNode* rear; void QueueEmpty(); }

Linked Queues Queue::Queue(){ front = 0; rear = 0; } bool Queue::isEmpty() { return (front == 0); } Front Rear 0 0

Linked Queues void Queue::Add(const int y) { // Create a new node that contains data y // Has to go at end // Set current rear link to new node pointer // Set new rear pointer to new node pointer rear = rear->link = new QueueNode(y, 0); } CAT Front MAT HAT Rear

Linked Queues int * Queue::Delete(int & retValue) { // handle empty case if (isEmpty()) { QueueEmpty(); return 0;} QueueNode* toDelete = front; retValue = toDelete.data; front = toDelete->link; delete toDelete; return &retValue; } CAT Front MAT HAT ReartoDelete HAT returnValue Front

Queue Destructor Queue destructor needs to remove all nodes from head to tail. CAT Front MAT HAT RearFront Temp 0 0 if (front) { QueueNode* temp; while (front != rear) { temp = front; front = front -> link; delete temp; } delete front; front = rear = 0; }

Front vs Delete Implementation as written has to remove the item from the queue to read data value. Implementation as written has to remove the item from the queue to read data value. Some implementations provide two separate functions: Some implementations provide two separate functions: Front() which returns the data in the first element Front() which returns the data in the first element Delete() which removes the first element from the queue, without returning a value. Delete() which removes the first element from the queue, without returning a value.

Queue Example: Radix Sort Also called bin sort: Repeatedly shuffle data into small bins Collect data from bins into new deck Repeat until sorted Appropriate method of shuffling and collecting? For integers, key is to shuffle data into bins on a per digit basis, starting with the rightmost (ones digit) Collect in order, from bin 0 to bin 9, and left to right within a bin

Radix Sort: Ones Digit Data: Bin 0 Bin 1 Bin Bin 3 Bin Bin 5 Bin 6 Bin Bin 8 Bin After Call: After Call:

Radix Sort: Tens Digit Data: Bin 0 Bin 1 Bin 2 Bin Bin Bin Bin 6 Bin Bin 8 Bin 9 After Call:

Radix Sort: Hundreds Digit Data: Bin 0 Bin 1 Bin Bin 3 Bin Bin Bin Bin 7 Bin 8 Bin 9 Final Sorted Data:

Radix Sort Algorithm Begin with current digit as one’s digit While there is still a digit on which to classify { For each number in the master list, Add that number to the appropriate sublist keyed on the current digit For each sublist from 0 to 9 For each number in the sublist Remove the number from the sublist and append to a new master list Advance the current digit one place to the left. }

Radix Sort and Queues What does radix sort have to do with queues? Each list (the master list (all items) and bins (per digit)) needs to be first in, first out ordered – perfect for a queue.

A Quick Tangent How fast have the sorts you’ve seen before worked? How fast have the sorts you’ve seen before worked? Bubble, Insertion, Selection: O(n^2) Bubble, Insertion, Selection: O(n^2) We will see sorts that are better, and in fact optimal for general sorting algorithms: We will see sorts that are better, and in fact optimal for general sorting algorithms: Merge/Quicksort: O(n log n) Merge/Quicksort: O(n log n) How fast is radix sort? How fast is radix sort?

Analysis of Radix Sort Let n be the number of items to sort Let n be the number of items to sort Outer loop control is on maximum length of input numbers in digits (Let this be d) Outer loop control is on maximum length of input numbers in digits (Let this be d) For every digit, For every digit, Assign each number to sort to a group (n operations) Assign each number to sort to a group (n operations) Pull each number back into the master list (n operations) Pull each number back into the master list (n operations) Overall running time: 2 * n * d => O(n) Overall running time: 2 * n * d => O(n)

Analysis of Radix Sort O(n log n) is optimal for general sorting algorithms O(n log n) is optimal for general sorting algorithms Radix sort is O(n)? How does that work? Radix sort is O(n)? How does that work? Radix sort is not a general sorting algorithm – It can’t sort arbitrary information – Rectangles objects, Automobiles objects, etc are no good. Radix sort is not a general sorting algorithm – It can’t sort arbitrary information – Rectangles objects, Automobiles objects, etc are no good. Can sort items that can be broken into constituent pieces and whose pieces can be ordered Can sort items that can be broken into constituent pieces and whose pieces can be ordered Integers (digits), Strings (characters) Integers (digits), Strings (characters)