SlideShare una empresa de Scribd logo
1 de 53
Queue
1
By:
Dabal Singh Mahara
2017
Unit – 4
Contents Hours Marks
a. Concept and definition
b. Queue as ADT
c. Implementation of Insert and Delete Operations Of:
• Linear Queue
• Circular Queue
d. Concept of Priority Queue
4 5
2
3
What is a Queue?
• A Queue is an ordered collection of items in which items are inserted at one
end (called the rear of the queue) and items are deleted at the other end (the
front of the queue).
• Since the first element inserted into the queue is the first element to be
removed, a queue is sometimes called a FIFO (first-in first-out) list as
opposed to the stack, which is a LIFO (last-in first-out).
Items [ MAX-1]
…
Items [4]
Items[3] D rear
Items[2] C
Items [1] B
Items [0] A front
Operations on Queue
• Some of the typical operations performed on queues are:
 MakeEmpty(q): To make q as an empty queue
 Enqueue(q, x): To insert an item x at the rear of the queue, this is also
called by names add, insert.
 Dequeue(q): To delete an item from the front of the queue q. This is also
known as delete, remove.
 IsFull(q): To check whether the queue q is full.
 IsEmpty(q): To check whether the queue q is empty
 Traverse (q): To read entire queue that is display the content of the queue.
4
Insertion of data into Queue
Insert( 3)
front =0
increment rear
i.e. rear = rear + 1
rear =0
front =0
rear = -1
front 3
Insert( 5)
front =0
rear =1 5
3
5
Insert( 10)
front =0
rear =2
5
3
10
Insertion of data into Queue
Insert( 8) rear = 3
3
5
10
8
front = 0
6
Deletion of data from the queue
rear = 3
3
5
10
8
front = 0
Delete( )
rear = 3
5
10
8
front = 1
increment front
i.e. front = front + 1
7
Delete( )
rear = 3
10
8
front = 2
Deletion of data from the queue
increment front
i.e. front = front + 1
8
Applications of Queue
• The queue is very useful in the various fields of computer science.
The applications can be listed as below:
 Access to shared resources: with in computer system there may be queues
of tasks waiting for the printer, for access to disk storage, or even in a time-
sharing system, for use of the CPU.
 Task scheduling in operating system
 Queue can be used as an auxiliary data structure for implementing various
algorithms.
9
The Queue as a ADT
• A queue q of type T is a finite sequence of elements with the
operations.
 MakeEmpty(q): To make q as an empty queue
 IsEmpty(q): To check whether the queue q is empty. Return true if q is empty,
return false otherwise.
 IsFull(q): To check whether the queue q is full. Return true in q is full, return
false otherwise.
 Enqueue(q, x): To insert an item x at the rear of the queue, if and only if q is not
full.
 Dequeue(q): To delete an item from the front of the queue q. if and only if q is
not empty.
 Traverse (q): To read entire queue that is display the content of the queue.
10
Implementation of Queue
• Queue can be implemented in two ways:
1. Array Implementation of queue(or static implementation)
2. Linked list implementation of queue (or dynamic)
• Array (static) implementation of a queue:
• It implements a queue using a one dimensional array to store the data.
• Two integer variables front and rear are used to indicate front and rear index of the
queue items.
• Further array implementation may be linear or circular.
11
Linear Array implementation
• This implementation uses a linear array with two indices rear and front that are
always increasing.
• Linear array implementation is also called linear queue.
#define MAX 10
struct queue
{
int items[MAX]; //Declaring an array to store items
int rear; // rear of queue
int front // front of queue
};
struct queue q;
• Initialization of front and rear front = 0 and rear = -1 12
Creating Empty queue
• The value of rear =-1 indicates the empty queue in C
implementation.
• /*Function to create an empty queue*/
void create_empty_queue(struct queue *q)
{
q->rear =-1;
q->front =0;
}
13
Queue Empty or Underflow
• This is the situation when the queue contains no element.
• At this point, the queue satisfies the condition rear < front .
• The following function return 1 if the queue is empty, 0 otherwise.
• int isempty(struct queue *q)
{
if(q->rear < q->front)
return 1;
else
return 0;
}
14
Queue Full or Overflow
• This is the situation when the queue becomes full, and no more elements
can be inserted into the queue.
• At this point the queue rear is present at the highest location (MAXSIZE- 1) of
the queue.
• The following function returns true (1) if queue is full false (0) otherwise.
• int isfull(struct queue *q)
{
if(q->rear==MAX-1)
return 1;
else
return 0;
}
15
Insert operation on queue
• Let queue[MAX] be an array to implement the queue.
• The variables rear and front denotes the rear and front of the queue.
• Insert operation adds one element 'item' to the queue.
• Algorithm for INSERT operation:
1. [Check for queue overflow?]
if rear=MAXSIZE-1 then
print “queue Overflow” and Exit
else
Set rear = rear+1 [Increase rear by 1]
Set queue[rear]:= item [Inserts item in new top position]
2. Exit
16
The function for Insert Operation
Void insert ( struct queue *q, int newitem)
{
if(IsFull(q))
{
printf(“queue is full”);
exit(1);
}
else
{
q->rear++;
q->items[q->rear]=newitem;
}
} 17
Delete operation
• This operation removes an item from the queue at front end and assigns it
to a variable item
• Algorithm:
1.[Check for the queue Underflow]
If rear < front then
Print “queue Underflow” and Exit
else [Remove the front element]
Set item=queue [front]
Set front=front + 1 [Increment front by 1]
Return the deleted item from the queue
2. Exit
18
The C function for Delete operation
void del(struct queue *q)
{
if(isempty(q))
printf("nn queue Underflow: Empty queue!!!");
else
printf("nthe deleted item is %d:t", q->items[q->front++]);
/*deletes an element pointed by front and increments front by 1 */
}
19
The display Function
void display( struct queue *q)
{
int i;
if(q->rear < q->front)
{
printf("Queue is emptyn");
}
else
{
For(i=q->front; i<=q->rear ; i ++)
printf("%dt", q->item[i]);
}
20
Problems with Linear queue implementation
• Both rear and front indices are increased but never decreased.
• As items are removed from the queue, the storage space at the beginning of
the array is discarded and never used again.
• Wastage of the space is the main problem with linear queue which is illustrated
by the following example.
• This queue is considered full, even though the space at beginning is vacant.
• One solution to this problem is to modify the delete operation so that when an
element is deleted, the entire queue is shifted to the beginning of the array.
That is, delete always at 0th location.
21
Modification of Delete Operations
void delete_item ( struct queue *q)
{ int i;
if(q->rear == -1)
{ printf("Queue is emptyn");
exit(1);
}
else
{
printf("n deleted item is %d", q->items [0]);
For(i=q->front; i<q->rear ; i ++)
q->item[i]= q->items[i+1];
q-> rear --;
}
} 22
Circular Queue
• A circular queue is one in which the insertion of a new element is
done at very first location of the queue if the last location of the queue
is full, as long as that first cell is empty.
• A circular queue overcomes the problem of unutilized space
in linear queue implementation as array.
• While implementing circular queue, we can use two approaches
 using global variable count to keep track of every insertion
and deletion operation
 Sacrificing one cell vacant
10 5 6 7 8 10
0 1 2 3 4 5
23
Sacrificing One Cell Vacant
• In array implementation of circular queue, the incrementing operation is
used for ease:
rear = (rear +1) % MAX
front = (front + 1) % MAX
• Both front and rear are initialized to MAX -1.
i.e. rear = MAX -1 and front = MAX - 1
• This initialization has empty situation: front == rear
• When we insert elements in the queue, the overflow situation is also same:
front == rear.
• To resolve this conflict, we sacrifice one cell of the array as a vacant thus to
insert n elements in a circular queue we need an array of size n + 1.
• That is, we can insert one less than the size of the array in circular queue.
• This problem can also be solved by using a global counter variable.
24
Declaration of a Circular Queue
• The declaration of circular queue is same as that of linear queue.
# define MAX 10 /* size of the circular queue items*/
struct cqueue
{
int front;
int rear;
int items[MAX];
};
struct cqueue cq;
• Initialization of rear and front
cq.rear = MAX -1; cq.front = MAX - 1
25
Operations of a circular queue
• The operations on a circular queue are also same as that
of linear queue.
1. makeEmpty queue
void makeEmpty(struct cqueue *q)
{
q->rear = MAX-1;
q->front = MAX-1;
}
26
2. Overflow and Underflow Tests
int IsEmpty( struct cqueue *q)
{
if(q->rear == q->front)
return 1;
else
return 0;
}
int IsFull(struct cqueue *q)
{
if(q->front==(q->rear+1)%MAX)
return 1;
else
return 0;
}
• IsFull Test • IsEmpty Test
27
3. Inserting an element in a circular queue
• Assume that rear and front are initially set to MAX-1.
• Cqueue is array to hold items and item is new element to be
added.
• Algorithm:
1. if (front == (rear+1)%MAX)
print Queue is full and exit
2. else
rear = (rear+1)%MAX; [increment rear by 1]
cqueue[rear] = item;
3. end
28
4. Deletion from Circular Queue
• Assume that rear and front are initially set to MAX-1.
• Cqueue is array that holds items.
• Algorithm
1. if (rear == front) [checking empty condition]
print Queue is empty
exit
2. Else
front=(front+1)%MAX; [increment front by 1]
item=cqueue[front];
return item;
3. end.
29
The Enqueue function:
void Enqueue(struct cqueue*q, int newitem)
{
if(IsFull(q))
{
printf(“queue is full”);
exit(1);
}
else
{
q->rear=(q->rear+1)%MAX;
q->items[q->rear]=newitem;
}
}
30
The Dequeue function
int Dequeue(struct cqueue *q)
{
if(IsEmpty(q))
{
printf(“queue is Empty”);
exit(1);
}
else
{
q->front = (q->front+1)%MAX;
return(q->items[q->front]);
}
}
31
Display Function
32
void display(struct cqueue *q)
{
int i;
if(q->rear==q->front)
printf("Queue is emptyn");
else
{
printf("Items of queue are:n");
for(i=(q->front+1)%MAX;i!=q->rear;i=(i+1)% MAX
{
printf("%dt",q->item[i]);
}
printf("%dt",q->item[q->rear]);
}
}
Circular Queue Using Global Counter
• To avoid loss of one array cell , a global integer variable "count" is used.
• Circular queue declaration is same as before:
#define MAX 10
struct cqueue
{
int item[MAX];
int rear;
int front;
};
struct cqueue cq;
• Global counter variable: int count = 0;
• Initialization:
int cq.front = MAX-1;
int cq.rear = MAX-1;
33
Insert Function
void insert(struct cqueue *q)
{
int d;
if(count==MAX)
printf("Queue is fulln");
else
{
q->rear=(q->rear+1)%MAX;
printf ("Enter data to be insertedn");
scanf("%d", &d);
q->item[q->rear] = d;
count++;
}
}
34
Delete Function
void deletion (struct cqueue *q)
{
if(count==0)
printf("Queue is emptyn");
else
{
q->front = (q->front+1)%MAX;
printf (" Deleted Item is t");
printf("%d", q->item[q->front]);
count--;
}
}
35
void display(struct cqueue *q)
{
int i;
if(q->rear == q->front)
printf("Queue is emptyn");
else
{
printf("Items of queue are:n");
for(i=(q->front+1)%MAX; i!=q->rear; i=(i +1)%MAX)
{
printf("%dt",q->item[i]);
}
printf("%dt",q->item[q->rear]);
}
}
Display Function
36
Priority Queue
• A priority queue is a collection of elements such that
each element has been assigned a priority and the order
in which elements are deleted according to the following
rules:
 An element of higher priority is processed before any element of lower
priority.
 If two elements has same priority then they are processed according to
the order in which they were added to the queue.
37
Application of Priority Queue
• In a time-sharing computer system, a large number of tasks may be
waiting for the CPU, some of these tasks have higher priority than
others. The set of tasks waiting for the CPU forms a priority queue.
• The jobs which have higher priority are processed first.
• If the priority of two jobs is same this jobs are processed according to
their position in queue.
• A shorter job is given higher priority over the longer one.
38
Types of priority queues
• Ascending priority queue(min priority queue):
 An ascending priority queue is a collection of items into which items
can be inserted arbitrarily but from which only the smallest item can
be removed.
• Descending priority queue(max priority queue):
 An descending priority queue is a collection of items into which items
can be inserted arbitrarily but from which only the largest item can be
removed.
39
Priority QUEUE Operations
• Insertion : The insertion in Priority queues is the same as in non-priority
queues.
• Deletion : Deletion requires a search for the element of highest
priority and deletes the element with highest priority.
• The following methods can be used for deletion/removal from a given
Priority Queue:
 An empty indicator replaces deleted elements.
 After each deletion elements can be moved up in the array
decrementing the rear.
 The array in the queue can be maintained as an ordered circular
array
40
The priority queue ADT
A ascending priority queue of elements of type T is a finite sequence of
elements of T together with the operations:
• MakeEmpty(p): Create an empty priority queue p
• Empty(p): Determine if the priority queue p is empty or not
• Insert(p,x): Add element x on the priority queue p
• DeleteMin(p): If the priority queue p is not empty, remove the
minimum element of the queque and return it.
• FindMin(p): Retrieve the minimum element of the priority queue p.
41
Array implementation of priority queue
Unordered array implementation
• To insert an item, insert it at the rear end of the queue.
• To delete an item, find the position of the minimum
element and
 Either mark it as deleted (lazy deletion) or
 shift all elements past the deleted element by on position
and then decrement rear.
42
55 39 77 44
f r
43
Illustration of unordered array implementation
Insert (65)
55 39 77 44 65
f r
deleteMin( )
55 -1 77 44 65
f r
Deleted
55 -1 77 -1 65
f r
deleteMin( )
Priority Queue Declaration
44
• Queue data type of Priority Queue is the same as the Non-
priority Queue.
#define MAX 10 /* size of the queue items*/
struct pqueue
{
int items[MAX];
int front;
int rear;
};
Insert Function
45
void insert( struct pqueue *q)
{
int x;
if(q->rear==MAX-1)
printf("Queue is fulln");
else
{
printf ("Enter data to be insertedn");
scanf("%d",&d);
q->rear++;
q->items[q->rear]=x;
}
}
46
Delete Function void delet( struct pqueue *q)
{
int i, temp=0, x;
if(q->rear < q->front)
{
printf("Queue is emptyn");
return 0;
}
else
{
x=q->items[q->front];
for(i=q->front+1; i<=q->rear; i++)
{
if(q->items[i] < x)
{
x=q->items[i];
temp=i;
}
}
for(i=temp;i< q->rear;i++)
{
q->items[i]=q->items[i+1];
}
q->rear--;
Printf("n Deleted item is %d ",x);
}
}
47
void display(pq *q)
{
int i;
if(q->rear < q->front)
printf("Queue is emptyn");
else
{
printf("Items of queue are:n");
for(i=q->front; i<=q->rear;i++)
{
printf("%dt", q->item[i]);
}
}
}
Display Function
Ordered array implementation
48
• In this implementation, the front is the position of the smallest
element and the rear is the position of the largest element.
• To insert an element, locate the proper position of the new
element and shift succeeding elements by one position.
• To delete the minimum element, delete element at the front
position and shift all elements one position towards front and
decrement rear.
49
Ordered array implementation
Insert Function
50
void insert(struct pqueue *q)
{
int x,i,j;
if(q->rear == MAX -1)
printf("n Queue is fulln");
else
{
printf ("nEnter data to be insertedt");
scanf("%d",&x);
for(i=q->front;i<=q->rear;i++)
{
if(x < q->item[i])
{
break;
}
}
for(j=q->rear;j>=i;j--)
q->item[j+1]= q->item[j];
q->rear = q->rear+1;
q->item[i] = x;
}
}
Delete Function
51
void delet(struct pqueue *q)
{
int i, x;
if(q->rear < q->front)
{
printf("nQueue is emptyn");
}
else
{ x=q->item[q->front];
for(i=q->front;i<q->rear;i++)
{
q->item[i]=q->item[i+1];
}
q->rear--;
printf("n Deleted item is %d", x);
}
}
Homework #5
1. How can you use queue as ADT?
2. Write a Menu program to demonstrate he simulation of queue operations in array
implementation.
3. Write a C function to display all items in the circular queue. Write assumptions
you need.
4. Write circular queue operations in array implementation.
5. What is a priority queue? How is it best implemented?
6. Define queue as an ADT. Write a program for basic operations in Linear queues
in array implementation.
Thank You !
53

Más contenido relacionado

La actualidad más candente (20)

Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix Notations
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Queue in Data Structure
Queue in Data Structure Queue in Data Structure
Queue in Data Structure
 
Queues
QueuesQueues
Queues
 
Expression trees
Expression treesExpression trees
Expression trees
 
Infix to Postfix Conversion Using Stack
Infix to Postfix Conversion Using StackInfix to Postfix Conversion Using Stack
Infix to Postfix Conversion Using Stack
 
Stack application
Stack applicationStack application
Stack application
 
Introduction to stack
Introduction to stackIntroduction to stack
Introduction to stack
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structure
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
stack presentation
stack presentationstack presentation
stack presentation
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Graph traversals in Data Structures
Graph traversals in Data StructuresGraph traversals in Data Structures
Graph traversals in Data Structures
 
Queue
QueueQueue
Queue
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
 
Heaps & priority queues
Heaps & priority queuesHeaps & priority queues
Heaps & priority queues
 
Circular queue
Circular queueCircular queue
Circular queue
 
Array data structure
Array data structureArray data structure
Array data structure
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data Structure
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
 

Similar a Unit 4 queue

Similar a Unit 4 queue (20)

Unit – iv queue
Unit – iv    queueUnit – iv    queue
Unit – iv queue
 
Queue(lecture8).pptx
Queue(lecture8).pptxQueue(lecture8).pptx
Queue(lecture8).pptx
 
Queue
QueueQueue
Queue
 
LEC4-DS ALGO.pdf
LEC4-DS  ALGO.pdfLEC4-DS  ALGO.pdf
LEC4-DS ALGO.pdf
 
@Chapter 4 DSA Part II.pptx
@Chapter 4 DSA Part II.pptx@Chapter 4 DSA Part II.pptx
@Chapter 4 DSA Part II.pptx
 
Queue AS an ADT (Abstract Data Type)
Queue AS an ADT (Abstract Data Type)Queue AS an ADT (Abstract Data Type)
Queue AS an ADT (Abstract Data Type)
 
Queues & ITS TYPES
Queues & ITS TYPESQueues & ITS TYPES
Queues & ITS TYPES
 
Unit 5 dsa QUEUE
Unit 5 dsa QUEUEUnit 5 dsa QUEUE
Unit 5 dsa QUEUE
 
Unit ii linear data structures
Unit ii linear data structures Unit ii linear data structures
Unit ii linear data structures
 
Data Structures - Lecture 6 [queues]
Data Structures - Lecture 6 [queues]Data Structures - Lecture 6 [queues]
Data Structures - Lecture 6 [queues]
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 
2 b queues
2 b queues2 b queues
2 b queues
 
Queues presentation
Queues presentationQueues presentation
Queues presentation
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURES
 
Data structure.ppt
Data structure.pptData structure.ppt
Data structure.ppt
 
Queue by rajanikanth
Queue by rajanikanthQueue by rajanikanth
Queue by rajanikanth
 
6 chapter3 list_stackqueuepart3
6 chapter3 list_stackqueuepart36 chapter3 list_stackqueuepart3
6 chapter3 list_stackqueuepart3
 
QUEUES
QUEUESQUEUES
QUEUES
 
Queue
QueueQueue
Queue
 
Data Structures - Lecture 2 - Unit 2.pptx
Data Structures - Lecture 2 - Unit 2.pptxData Structures - Lecture 2 - Unit 2.pptx
Data Structures - Lecture 2 - Unit 2.pptx
 

Más de Dabbal Singh Mahara (19)

Temporal databases
Temporal databasesTemporal databases
Temporal databases
 
Spatial databases
Spatial databasesSpatial databases
Spatial databases
 
Ordbms
OrdbmsOrdbms
Ordbms
 
Odbms concepts
Odbms conceptsOdbms concepts
Odbms concepts
 
Object database standards, languages and design
Object database standards, languages and designObject database standards, languages and design
Object database standards, languages and design
 
Normalization
NormalizationNormalization
Normalization
 
Mobile databases
Mobile databasesMobile databases
Mobile databases
 
Active database
Active databaseActive database
Active database
 
Deductive databases
Deductive databasesDeductive databases
Deductive databases
 
Relational model
Relational modelRelational model
Relational model
 
Overview of dbms
Overview of dbmsOverview of dbms
Overview of dbms
 
ER modeling
ER modelingER modeling
ER modeling
 
EER modeling
EER modelingEER modeling
EER modeling
 
Unit 9 graph
Unit   9 graphUnit   9 graph
Unit 9 graph
 
Unit 7 sorting
Unit   7 sortingUnit   7 sorting
Unit 7 sorting
 
Unit 6 tree
Unit   6 treeUnit   6 tree
Unit 6 tree
 
Unit 5 linked list
Unit   5 linked listUnit   5 linked list
Unit 5 linked list
 
Unit 8 searching and hashing
Unit   8 searching and hashingUnit   8 searching and hashing
Unit 8 searching and hashing
 
Unit 2 algorithm
Unit   2 algorithmUnit   2 algorithm
Unit 2 algorithm
 

Último

CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptMsecMca
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoordharasingh5698
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 

Último (20)

CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 

Unit 4 queue

  • 2. Unit – 4 Contents Hours Marks a. Concept and definition b. Queue as ADT c. Implementation of Insert and Delete Operations Of: • Linear Queue • Circular Queue d. Concept of Priority Queue 4 5 2
  • 3. 3 What is a Queue? • A Queue is an ordered collection of items in which items are inserted at one end (called the rear of the queue) and items are deleted at the other end (the front of the queue). • Since the first element inserted into the queue is the first element to be removed, a queue is sometimes called a FIFO (first-in first-out) list as opposed to the stack, which is a LIFO (last-in first-out). Items [ MAX-1] … Items [4] Items[3] D rear Items[2] C Items [1] B Items [0] A front
  • 4. Operations on Queue • Some of the typical operations performed on queues are:  MakeEmpty(q): To make q as an empty queue  Enqueue(q, x): To insert an item x at the rear of the queue, this is also called by names add, insert.  Dequeue(q): To delete an item from the front of the queue q. This is also known as delete, remove.  IsFull(q): To check whether the queue q is full.  IsEmpty(q): To check whether the queue q is empty  Traverse (q): To read entire queue that is display the content of the queue. 4
  • 5. Insertion of data into Queue Insert( 3) front =0 increment rear i.e. rear = rear + 1 rear =0 front =0 rear = -1 front 3 Insert( 5) front =0 rear =1 5 3 5
  • 6. Insert( 10) front =0 rear =2 5 3 10 Insertion of data into Queue Insert( 8) rear = 3 3 5 10 8 front = 0 6
  • 7. Deletion of data from the queue rear = 3 3 5 10 8 front = 0 Delete( ) rear = 3 5 10 8 front = 1 increment front i.e. front = front + 1 7
  • 8. Delete( ) rear = 3 10 8 front = 2 Deletion of data from the queue increment front i.e. front = front + 1 8
  • 9. Applications of Queue • The queue is very useful in the various fields of computer science. The applications can be listed as below:  Access to shared resources: with in computer system there may be queues of tasks waiting for the printer, for access to disk storage, or even in a time- sharing system, for use of the CPU.  Task scheduling in operating system  Queue can be used as an auxiliary data structure for implementing various algorithms. 9
  • 10. The Queue as a ADT • A queue q of type T is a finite sequence of elements with the operations.  MakeEmpty(q): To make q as an empty queue  IsEmpty(q): To check whether the queue q is empty. Return true if q is empty, return false otherwise.  IsFull(q): To check whether the queue q is full. Return true in q is full, return false otherwise.  Enqueue(q, x): To insert an item x at the rear of the queue, if and only if q is not full.  Dequeue(q): To delete an item from the front of the queue q. if and only if q is not empty.  Traverse (q): To read entire queue that is display the content of the queue. 10
  • 11. Implementation of Queue • Queue can be implemented in two ways: 1. Array Implementation of queue(or static implementation) 2. Linked list implementation of queue (or dynamic) • Array (static) implementation of a queue: • It implements a queue using a one dimensional array to store the data. • Two integer variables front and rear are used to indicate front and rear index of the queue items. • Further array implementation may be linear or circular. 11
  • 12. Linear Array implementation • This implementation uses a linear array with two indices rear and front that are always increasing. • Linear array implementation is also called linear queue. #define MAX 10 struct queue { int items[MAX]; //Declaring an array to store items int rear; // rear of queue int front // front of queue }; struct queue q; • Initialization of front and rear front = 0 and rear = -1 12
  • 13. Creating Empty queue • The value of rear =-1 indicates the empty queue in C implementation. • /*Function to create an empty queue*/ void create_empty_queue(struct queue *q) { q->rear =-1; q->front =0; } 13
  • 14. Queue Empty or Underflow • This is the situation when the queue contains no element. • At this point, the queue satisfies the condition rear < front . • The following function return 1 if the queue is empty, 0 otherwise. • int isempty(struct queue *q) { if(q->rear < q->front) return 1; else return 0; } 14
  • 15. Queue Full or Overflow • This is the situation when the queue becomes full, and no more elements can be inserted into the queue. • At this point the queue rear is present at the highest location (MAXSIZE- 1) of the queue. • The following function returns true (1) if queue is full false (0) otherwise. • int isfull(struct queue *q) { if(q->rear==MAX-1) return 1; else return 0; } 15
  • 16. Insert operation on queue • Let queue[MAX] be an array to implement the queue. • The variables rear and front denotes the rear and front of the queue. • Insert operation adds one element 'item' to the queue. • Algorithm for INSERT operation: 1. [Check for queue overflow?] if rear=MAXSIZE-1 then print “queue Overflow” and Exit else Set rear = rear+1 [Increase rear by 1] Set queue[rear]:= item [Inserts item in new top position] 2. Exit 16
  • 17. The function for Insert Operation Void insert ( struct queue *q, int newitem) { if(IsFull(q)) { printf(“queue is full”); exit(1); } else { q->rear++; q->items[q->rear]=newitem; } } 17
  • 18. Delete operation • This operation removes an item from the queue at front end and assigns it to a variable item • Algorithm: 1.[Check for the queue Underflow] If rear < front then Print “queue Underflow” and Exit else [Remove the front element] Set item=queue [front] Set front=front + 1 [Increment front by 1] Return the deleted item from the queue 2. Exit 18
  • 19. The C function for Delete operation void del(struct queue *q) { if(isempty(q)) printf("nn queue Underflow: Empty queue!!!"); else printf("nthe deleted item is %d:t", q->items[q->front++]); /*deletes an element pointed by front and increments front by 1 */ } 19
  • 20. The display Function void display( struct queue *q) { int i; if(q->rear < q->front) { printf("Queue is emptyn"); } else { For(i=q->front; i<=q->rear ; i ++) printf("%dt", q->item[i]); } 20
  • 21. Problems with Linear queue implementation • Both rear and front indices are increased but never decreased. • As items are removed from the queue, the storage space at the beginning of the array is discarded and never used again. • Wastage of the space is the main problem with linear queue which is illustrated by the following example. • This queue is considered full, even though the space at beginning is vacant. • One solution to this problem is to modify the delete operation so that when an element is deleted, the entire queue is shifted to the beginning of the array. That is, delete always at 0th location. 21
  • 22. Modification of Delete Operations void delete_item ( struct queue *q) { int i; if(q->rear == -1) { printf("Queue is emptyn"); exit(1); } else { printf("n deleted item is %d", q->items [0]); For(i=q->front; i<q->rear ; i ++) q->item[i]= q->items[i+1]; q-> rear --; } } 22
  • 23. Circular Queue • A circular queue is one in which the insertion of a new element is done at very first location of the queue if the last location of the queue is full, as long as that first cell is empty. • A circular queue overcomes the problem of unutilized space in linear queue implementation as array. • While implementing circular queue, we can use two approaches  using global variable count to keep track of every insertion and deletion operation  Sacrificing one cell vacant 10 5 6 7 8 10 0 1 2 3 4 5 23
  • 24. Sacrificing One Cell Vacant • In array implementation of circular queue, the incrementing operation is used for ease: rear = (rear +1) % MAX front = (front + 1) % MAX • Both front and rear are initialized to MAX -1. i.e. rear = MAX -1 and front = MAX - 1 • This initialization has empty situation: front == rear • When we insert elements in the queue, the overflow situation is also same: front == rear. • To resolve this conflict, we sacrifice one cell of the array as a vacant thus to insert n elements in a circular queue we need an array of size n + 1. • That is, we can insert one less than the size of the array in circular queue. • This problem can also be solved by using a global counter variable. 24
  • 25. Declaration of a Circular Queue • The declaration of circular queue is same as that of linear queue. # define MAX 10 /* size of the circular queue items*/ struct cqueue { int front; int rear; int items[MAX]; }; struct cqueue cq; • Initialization of rear and front cq.rear = MAX -1; cq.front = MAX - 1 25
  • 26. Operations of a circular queue • The operations on a circular queue are also same as that of linear queue. 1. makeEmpty queue void makeEmpty(struct cqueue *q) { q->rear = MAX-1; q->front = MAX-1; } 26
  • 27. 2. Overflow and Underflow Tests int IsEmpty( struct cqueue *q) { if(q->rear == q->front) return 1; else return 0; } int IsFull(struct cqueue *q) { if(q->front==(q->rear+1)%MAX) return 1; else return 0; } • IsFull Test • IsEmpty Test 27
  • 28. 3. Inserting an element in a circular queue • Assume that rear and front are initially set to MAX-1. • Cqueue is array to hold items and item is new element to be added. • Algorithm: 1. if (front == (rear+1)%MAX) print Queue is full and exit 2. else rear = (rear+1)%MAX; [increment rear by 1] cqueue[rear] = item; 3. end 28
  • 29. 4. Deletion from Circular Queue • Assume that rear and front are initially set to MAX-1. • Cqueue is array that holds items. • Algorithm 1. if (rear == front) [checking empty condition] print Queue is empty exit 2. Else front=(front+1)%MAX; [increment front by 1] item=cqueue[front]; return item; 3. end. 29
  • 30. The Enqueue function: void Enqueue(struct cqueue*q, int newitem) { if(IsFull(q)) { printf(“queue is full”); exit(1); } else { q->rear=(q->rear+1)%MAX; q->items[q->rear]=newitem; } } 30
  • 31. The Dequeue function int Dequeue(struct cqueue *q) { if(IsEmpty(q)) { printf(“queue is Empty”); exit(1); } else { q->front = (q->front+1)%MAX; return(q->items[q->front]); } } 31
  • 32. Display Function 32 void display(struct cqueue *q) { int i; if(q->rear==q->front) printf("Queue is emptyn"); else { printf("Items of queue are:n"); for(i=(q->front+1)%MAX;i!=q->rear;i=(i+1)% MAX { printf("%dt",q->item[i]); } printf("%dt",q->item[q->rear]); } }
  • 33. Circular Queue Using Global Counter • To avoid loss of one array cell , a global integer variable "count" is used. • Circular queue declaration is same as before: #define MAX 10 struct cqueue { int item[MAX]; int rear; int front; }; struct cqueue cq; • Global counter variable: int count = 0; • Initialization: int cq.front = MAX-1; int cq.rear = MAX-1; 33
  • 34. Insert Function void insert(struct cqueue *q) { int d; if(count==MAX) printf("Queue is fulln"); else { q->rear=(q->rear+1)%MAX; printf ("Enter data to be insertedn"); scanf("%d", &d); q->item[q->rear] = d; count++; } } 34
  • 35. Delete Function void deletion (struct cqueue *q) { if(count==0) printf("Queue is emptyn"); else { q->front = (q->front+1)%MAX; printf (" Deleted Item is t"); printf("%d", q->item[q->front]); count--; } } 35
  • 36. void display(struct cqueue *q) { int i; if(q->rear == q->front) printf("Queue is emptyn"); else { printf("Items of queue are:n"); for(i=(q->front+1)%MAX; i!=q->rear; i=(i +1)%MAX) { printf("%dt",q->item[i]); } printf("%dt",q->item[q->rear]); } } Display Function 36
  • 37. Priority Queue • A priority queue is a collection of elements such that each element has been assigned a priority and the order in which elements are deleted according to the following rules:  An element of higher priority is processed before any element of lower priority.  If two elements has same priority then they are processed according to the order in which they were added to the queue. 37
  • 38. Application of Priority Queue • In a time-sharing computer system, a large number of tasks may be waiting for the CPU, some of these tasks have higher priority than others. The set of tasks waiting for the CPU forms a priority queue. • The jobs which have higher priority are processed first. • If the priority of two jobs is same this jobs are processed according to their position in queue. • A shorter job is given higher priority over the longer one. 38
  • 39. Types of priority queues • Ascending priority queue(min priority queue):  An ascending priority queue is a collection of items into which items can be inserted arbitrarily but from which only the smallest item can be removed. • Descending priority queue(max priority queue):  An descending priority queue is a collection of items into which items can be inserted arbitrarily but from which only the largest item can be removed. 39
  • 40. Priority QUEUE Operations • Insertion : The insertion in Priority queues is the same as in non-priority queues. • Deletion : Deletion requires a search for the element of highest priority and deletes the element with highest priority. • The following methods can be used for deletion/removal from a given Priority Queue:  An empty indicator replaces deleted elements.  After each deletion elements can be moved up in the array decrementing the rear.  The array in the queue can be maintained as an ordered circular array 40
  • 41. The priority queue ADT A ascending priority queue of elements of type T is a finite sequence of elements of T together with the operations: • MakeEmpty(p): Create an empty priority queue p • Empty(p): Determine if the priority queue p is empty or not • Insert(p,x): Add element x on the priority queue p • DeleteMin(p): If the priority queue p is not empty, remove the minimum element of the queque and return it. • FindMin(p): Retrieve the minimum element of the priority queue p. 41
  • 42. Array implementation of priority queue Unordered array implementation • To insert an item, insert it at the rear end of the queue. • To delete an item, find the position of the minimum element and  Either mark it as deleted (lazy deletion) or  shift all elements past the deleted element by on position and then decrement rear. 42
  • 43. 55 39 77 44 f r 43 Illustration of unordered array implementation Insert (65) 55 39 77 44 65 f r deleteMin( ) 55 -1 77 44 65 f r Deleted 55 -1 77 -1 65 f r deleteMin( )
  • 44. Priority Queue Declaration 44 • Queue data type of Priority Queue is the same as the Non- priority Queue. #define MAX 10 /* size of the queue items*/ struct pqueue { int items[MAX]; int front; int rear; };
  • 45. Insert Function 45 void insert( struct pqueue *q) { int x; if(q->rear==MAX-1) printf("Queue is fulln"); else { printf ("Enter data to be insertedn"); scanf("%d",&d); q->rear++; q->items[q->rear]=x; } }
  • 46. 46 Delete Function void delet( struct pqueue *q) { int i, temp=0, x; if(q->rear < q->front) { printf("Queue is emptyn"); return 0; } else { x=q->items[q->front]; for(i=q->front+1; i<=q->rear; i++) { if(q->items[i] < x) { x=q->items[i]; temp=i; } } for(i=temp;i< q->rear;i++) { q->items[i]=q->items[i+1]; } q->rear--; Printf("n Deleted item is %d ",x); } }
  • 47. 47 void display(pq *q) { int i; if(q->rear < q->front) printf("Queue is emptyn"); else { printf("Items of queue are:n"); for(i=q->front; i<=q->rear;i++) { printf("%dt", q->item[i]); } } } Display Function
  • 48. Ordered array implementation 48 • In this implementation, the front is the position of the smallest element and the rear is the position of the largest element. • To insert an element, locate the proper position of the new element and shift succeeding elements by one position. • To delete the minimum element, delete element at the front position and shift all elements one position towards front and decrement rear.
  • 50. Insert Function 50 void insert(struct pqueue *q) { int x,i,j; if(q->rear == MAX -1) printf("n Queue is fulln"); else { printf ("nEnter data to be insertedt"); scanf("%d",&x); for(i=q->front;i<=q->rear;i++) { if(x < q->item[i]) { break; } } for(j=q->rear;j>=i;j--) q->item[j+1]= q->item[j]; q->rear = q->rear+1; q->item[i] = x; } }
  • 51. Delete Function 51 void delet(struct pqueue *q) { int i, x; if(q->rear < q->front) { printf("nQueue is emptyn"); } else { x=q->item[q->front]; for(i=q->front;i<q->rear;i++) { q->item[i]=q->item[i+1]; } q->rear--; printf("n Deleted item is %d", x); } }
  • 52. Homework #5 1. How can you use queue as ADT? 2. Write a Menu program to demonstrate he simulation of queue operations in array implementation. 3. Write a C function to display all items in the circular queue. Write assumptions you need. 4. Write circular queue operations in array implementation. 5. What is a priority queue? How is it best implemented? 6. Define queue as an ADT. Write a program for basic operations in Linear queues in array implementation.