0% found this document useful (0 votes)
11 views62 pages

Queue ADT

The document provides an overview of the Queue Abstract Data Type (ADT), including its definition, basic operations (enqueue, dequeue, and peek), and implementations using arrays and linked lists. It also discusses priority queues, their operations, and real-life applications such as data categorization and queue simulation. Additionally, it covers the challenges of implementing queues with arrays, particularly the rightward drift problem, and solutions like circular arrays.

Uploaded by

Ahmed Wagih
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views62 pages

Queue ADT

The document provides an overview of the Queue Abstract Data Type (ADT), including its definition, basic operations (enqueue, dequeue, and peek), and implementations using arrays and linked lists. It also discusses priority queues, their operations, and real-life applications such as data categorization and queue simulation. Additionally, it covers the challenges of implementing queues with arrays, particularly the rightward drift problem, and solutions like circular arrays.

Uploaded by

Ahmed Wagih
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

CMP1040: Data Structures and Algorithms

Lecture 04: Queue ADT


Ahmed Hamdy
Computer Engineering Department
Cairo University
Agenda
▪ Queue definition
▪ Basic queue operations
▪ Implementing queue operations
– Array implementation
– Linked list / chain implementation
▪ Priority queues
▪ Applications using queue ADT
Queue
What is a Queue? FIFO
Basic Queue Operations

▪ Enqueue → Check queue_FULL

▪ Dequeue → Check queue_EMPTY

▪ Queue Front → Check queue_EMPTY

5
The Queue ADT
▪ UML diagram for the class Queue
In many cases it needs to return ItemType as follows
+dequeue(newEntry: ItemType&) : boolean

→ Check isFull AND isEmpty


→ for array and circular array impl.

6
Queue Operations: Enqueue
Queue Operations: Dequeue
Queue Operations: Peek Front

Peek
Front
Queue Example
Queue Example
Linked List Implementation
Linked List / Chain Implementation

There are two options:


1. Linked List → similar to List ADT

2. Linked Chain, where last node points to first node

13
Linked List / Chain Implementation
▪ How will the queue be declared?
▪ How will the queue be initialised? → Write a constructor
▪ How will the member functions be implemented? → note special
cases!
▪ Can the queue be implemented using a single pointer? What should
that pointer point to? Check out!

14
Linked List Implementation
Linked List Implementation: Structure
▪ Constructor?
▪ Enqueue?
▪ Dequeue?
▪ Special cases?
Linked List Implementation: Enqueue
Note: this case has to be
explicitly handled!
Linked List Implementation: Dequeue
Linked List Implementation: Dequeue

Note: this case has to


be explicitly handled!
Linked List Implementation: EmptyQueue
Linked List Implementation: FullQueue
Linked List Implementation: DestroyQueue
Linked Chain Implementation
▪ Circular chain
▪ Constructor?
▪ Enqueue?
▪ Dequeue?
▪ Special cases?
Array Implementation

▪ Refer to extra slides for array


implementation of queue at the end of
presentation.
Priority Queues
Real-life Priority Queue
▪ Example : triage in a hospital emergency room

Emergency patients have a priority!


Queues vs Priority Queue

▪ A priority queue is an ADT with the property that only the highest-
priority element can be accessed at any time, even if they are
enqued late.

▪ A priority queue has an additional measure for insertion (enque),


namely the priority of the element.
Queues vs Priority Queue
▪ Elements of higher priority are inserted first and in order of
occurrence w.r.t. elements of the same priority.
▪ Priority may be reprepresented by an integer value, e.g.1-10 with 10
having the highest priority.
▪ Priority Queue Operations:
▪ Enque a pair <item, priority>
▪ Dequeue: Item returned has the highest priority.
Queues vs Priority Queue
▪ How is the interface implemented now?
▪ Priority Queue Operations:
▪ Initially: (A,10), (X,10), (B, 7), (H,3), (R,2)
▪ Enque a pair <item, priority>
▪ Example: enqueue (M, 9)
▪ (A,10), (X,10), (M,9), (B, 7), (H,3), (R,2)
How is it implemented?.
Queues vs Priority Queue

▪ How is the interface implemented now ?


Dequeue: Item returned has the highest priority.
What is the modification?

No modification is required!
Applications using Queues ADT
Using queue as ADT!

Enqueue

→ Dequeue

Peek
Queue Applications

We consider two queue applications:

→ • Categorizing Data
• Queue Simulation
Data Categorization
▪ Goal: categorize data within a queue while maintaining relative
order.
▪ Examples:
– Students according to their scores
– Employees according to their age group
▪ Integers are categorized as : 0-10, 11-19, 20-29.
Data Categorization: Required Output
Data Categorization: Core Code
The general algorithm would be:

// assume q contains all data


while (q. dequeue ( data )) // read item from queue
{ cat = data/10 // category

if ( cat < 1 ) q0.enqueue (data); continue;

if ( cat < 2 ) q1.enqueue (data); continue;

if ( cat < 3 ) q2.enqueue (data); continue;

q3.enqueue.(data);
}

return;
Data Categorization: Structures
Data Categorization: Structures
Queue Simulator

Arrives: 7:00 Arrives: 7:40 Arrives: 7:45


Service time:
30 minutes

Starts: 7:00 Starts: 7:40 Starts: 8:10


Finishes: 7:30 Finishes: 8:10 Finishes: 8:40
Waiting: 0:00 Waiting: 0:00 Waiting: 0:25

slidetemplates.com
icon-icons.com/
Queue Simulator
▪ Queuing theory is a field of applied mathematics that is used to
predict the performance of queues.
▪ To simulate a queue, we need the following information for each
individual:

Customer Arrival Service Start Finish Wait time


ID time time Time Time
required
Queue Simulator: Factors
Definitions:
▪ Factors that mostly affect a queue’s performance are:
▪ Arrival Rate
probability of arrival = 1/Arrival Rate
▪ Service Time

▪ Ideally, arrival rate should match service time


▪ The goal is to predict the average wait time for each customer
(queue time )

42
Queue Simulator: Arrival Rate
Problem description:
• A customer arrives every m mins (arrival rate)
→ probability of a customer arriving at a certain instance? (1/m)
→ determine if a customer arrived at a certain instance or not
… use rand num generator

43
Queue Simulator: Arrival Time
▪ Now we want to answer the following question:
▪ At each instance: Did a new customer arrive?
▪ A common function used in these cases is the rand() function.
The most common form is
float rand()
that returns a value between 0 and 1.
→ So, assuming that probability of arrival of a customer is 25% if
rand() returns a value between 0 and 0.25 then we assume a
customer arrived, otherwise no customer arrived at this instance.

45
Queue Simulator: Service Time
▪ Another thing to determine is the customer service time
The rand function can be used to generate random values within any
required range. So a customer service time should be some random
value between min_servtime and max_servtime
Hence
Cust_servtime = min_servtime + rand()*(max_servtime – min_servtime)

Generates a random serv_time within the range:


(min_servtime, max_servtime)

46
Queue Simulator
To wrap-up:
Input:
▪ Probability of a new customer arriving,
▪ Max and min service time of a new customer
Output: Average wait time of customer is calculated
Algorithm: At each instance one or more of the following events may
occur:
▪ A new customer arrives
▪ The customer in front is served (finished)
In all cases time is incremented till simulation period finishes.

47
Queue Simulator: Example
Custom Arrival Service Start Finish Wait
er ID time time Time Time time
required
1 5 9 5 14 0
2 7 6 14 20 7
3 14 4 20 24 6
4 30 5 30 35 0
5 32 6 35 41 3
6 34 5 41 46 7

finish [i] = start [i] + service time

start [i] = finish [i-1] if finish [i-1] > arrival [i]


= arrival [i] otherwise
wait [i] = start [i] – arrival [i]
Array Implementation
Array Implementation
▪ How will the queue be declared?
▪ How will the queue be initialized?
▪ What is the problem with linear array and why do we use a circular
array?
▪ How do we check for empty and full in the circular array?
▪ How will the member functions be implemented?
Array Implementation
Now, assuming back points to first free location in queue then:
▪ Enqueue : arr[back] = it; back ++;
▪ IsEmpty : if back == front;
→ initialization back = front = 0
▪ Dequeue :
▪ check IsEmpty! ( front == back)
▪ return arr [front]; front++;
▪ IsFull == true if back = max – 1
→ false indication
▪ Rightward drift (refer to next slide)
Array Implementation

enqueue arr dequeue it =


[back++ ] = it arr [front++]
Initially
Although
Repeatingback == max-1
dequeue
enqueue atill the queue is
back = 0 NOT
backFULL.
couple There are free location at
==ofmax-1
times
front = 0 0→3

[0] [4] [max-1]


Array Implementation

▪ The basic problem of array implementation is the rightward


DRIFT. It causes a false ‘FULL’ indication (back == max – 1).
▪ There are several ways to solve it:
1. Shifting all elements left when back == max-1
2. Using circular array:
2.1. With additional variable count
2.2. Without variable count.
Array Implementation: Rightward Drift
How to solve rightward drift
problem?

1.Shift elements left when 2. Use Wrap around


back == max-1

2.1. Using extra variable 2.2. No count, consider


count pointer catch up
Array Implementation: Rightward Drift
1. The first solution is to shift all elements in array left
▪ When back == max-1
Move all elements left such that front points to index 0 and
all free elements are on the right.
front back

However, overhead of shift is high!


Array Implementation: Circular Array
2. Another solution is → using circular array. How is the next
index for front and back estimated?
▪ The next index of i (whether front or back) would be
int nextOf (int %indx)
(i+1) max { → WRAP AROUND!
return (indx+1)% max;}

So if i == max – 1 i.e. end of array, then next i would be 0


Array Implementation: Circular Array
▪ The previous Empty condition
back == front
is now invalid, as it is possible that back « wraps around » such
that back == front and yet queue is NOT empty
front back
Array Implementation: Circular Array

2. Two ways:
2.1. Use an additional count variable to follow enqueue and
dequeue and hence determine when the queue is full or empty.

2.2. No additional count , just track relative movement of front


and back pointers to determine queue empty and queue full.
Array Implementation: Circular Array
2.1. The first solution is to use variable count and modify the previous
procedures as follows:
▪ Initialization: front = 0; back = 0; hence count = 0
▪ Enqueue : arr[back] = it; back = (back + 1)% max; count ++
▪ Dequeue : count - -
▪ Check IsEmpty → ifcount
back == 0
< front;
▪ return arr [front]; front =(front+1)%max;
▪ IsFull == true count == max

59
Array Implementation: Circular Array
2. 2. Another solution is to get rid of count and watch
the relative position of front and back.
▪ However, the condition back == front may cause a
dilemma:
▪ Queue is becoming empty, as front has catched up with
back
▪ OR queue is becoming full, as back has catched up with
front
Array Implementation: Circular Array
▪ One option is to use the condition back == front
to indicate that queue is empty
▪ Then, queue full is indicated by:
(back+1) % max == front
i.e. back has catched up with front
The operations will be as follows ….
Array Implementation: Circular Array
▪ Initialize: front = back = 0;
▪ Hence, queue is EMPTY if front == back
▪ Operation enqueue:
arr [back] = it;
back = (back+1) % max;
▪ Operation dequeue: (provided that front != back)
it = arr [front]
front = (front+1) % max;
▪ Queue is FULL if (back+1) % max == front
i.e. back catched up with front
62
Array Implementation: Circular Array
▪ At this final case, FULL is true as
(back + 1) % max == front
▪ Then, enqueue will not succeed and this final location will NOT
be filled. i.e. only (max-1) locations out of max locations are
useful: back front

You might also like