SlideShare a Scribd company logo
1 of 27
Chapter 7
QUEUES
Dr. Muhammad Hanif Durad
Department of Computer and Information Sciences
Pakistan Institute Engineering and Applied Sciences
hanif@pieas.edu.pk
Some slides have bee adapted with thanks from some other lectures
available on Internet. It made my life easier, as life is always
miserable at PIEAS (Sir Muhammad Yusaf Kakakhil )
Dr. Hanif Durad 2
Lecture Outline
 Queues
 Deques
 Priority Queue
Visualization of a Queue
Dr. Hanif Durad 3
D:Data StructuresPRG DS CS11001L9-3.pdf
4
Queues, and Deques
 A queue is a first in, first out (FIFO) data structure
 Items are removed from a queue in the same order as they
were inserted
 A deque is a double-ended queue—items can be
inserted and removed at either end
D:Data StructuresHanif_SearchQueues23-stacks-queues-deques.ppt
Queue Applications
 Real life examples
 Waiting in line
 Waiting on hold for tech support
 Applications related to Computer Science
 Threads
 Job scheduling (e.g. Round-Robin algorithm for
CPU allocation)
Dr. Hanif Durad 5
D:Data StructuresCSCE3110Queues.ppt
6
Queues (1/2)
 A queue differs from a stack in that its insertion and removal
routines follows the first-in-first-out (FIFO) principle.
 Elements may be inserted at any time, but only the element which
has been in the queue the longest may be removed.
 Elements are inserted at the rear (enqueued) and removed from
the front (dequeued)
Front RearQueue
D:Data StructuresHanif_SearchQueues ad5.ppt,P-23
7
Queues (2/2)
 The queue supports three fundamental methods:
 New():ADT – Creates an empty queue
 Enqueue(S:ADT, o:element):ADT - Inserts object o at the rear
of the queue
 Dequeue(S:ADT):ADT - Removes the object from the front of
the queue; an error occurs if the queue is empty
 Front(S:ADT):element - Returns, but does not remove, the
front element; an error occurs if the queue is empty
8
Array implementation of queues
 A queue is a first in, first out (FIFO) data structure
 This is accomplished by inserting at one end (the rear) and
deleting from the other (the front)
 To insert: put new element in location 4, and set rear to 4
 To delete: take element from location 0, and set front to 1
17 23 97 44
0 1 2 3 4 5 6 7
myQueue:
rear = 3front = 0
D:Data StructuresHanif_SearchQueues23-stacks-queues-deques.ppt
9
Array implementation of queues
 Notice how the array contents “crawl” to the right as elements are
inserted and deleted
 This will be a problem after a while!
17 23 97 44 333After insertion:
23 97 44 333After deletion:
rear = 4front = 1
17 23 97 44Initial queue:
rear = 3front = 0
10
Circular arrays
 We can treat the array holding the queue elements as
circular (joined at the ends)
44 55 11 22 33
0 1 2 3 4 5 6 7
myQueue:
rear = 1 front = 5
 Elements were added to this queue in the order 11, 22,
33, 44, 55, and will be removed in the same order
 Use: front = (front + 1) % myQueue.length;
and: rear = (rear + 1) % myQueue.length;
11
Full and empty queues
 If the queue were to become completely full, it would look
like this:
 If we were then to remove all eight elements, making the queue
completely empty, it would look like this:
44 55 66 77 88 11 22 33
0 1 2 3 4 5 6 7
myQueue:
rear = 4 front = 5
0 1 2 3 4 5 6 7
myQueue:
rear = 4 front = 5
This is a problem!
12
Full and empty queues: solutions
 Solution #1: Keep an additional variable
 Solution #2: (Slightly more efficient) Keep a gap between
elements: consider the queue full when it has n-1 elements
44 55 66 77 88 11 22 33
0 1 2 3 4 5 6 7
myQueue:
rear = 4 front = 5count = 8
44 55 66 77 11 22 33
0 1 2 3 4 5 6 7
myQueue:
rear = 3 front = 5
Queue Implementation using
Linked List
 Basic idea:
 Create a linked list to which items would be added to one end and deleted
from the other end.
 Two pointers will be maintained:
 One pointing to the beginning of the list (point fromwhere elements will be
deleted). <Front>
 Another pointing to the end of the list (point where new elements will be
inserted). <Rear>
13
D:Data StructuresPRG DS CS11001L9-3.pdf
14
Linked-list implementation of queues
 In a queue, insertions occur at one end, deletions at
the other end
 Operations at the front of a singly-linked list (SLL)
are O(1), but at the other end they are O(n)
 Because you have to find the last element each time
 BUT: there is a simple way to use a singly-linked
list to implement both insertions and deletions in
O(1) time
 You always need a pointer to the first thing in the list
 You can keep an additional pointer to the last thing in the
list
15
Enqueueing a node
17
Node to be
enqueued
To enqueue (add) a node:
Find the current last node
Change it to point to the new last node
Change the last pointer in the list header
2344
last
first
97
16
Dequeueing a node
 To dequeue (remove) a node:
 Copy the pointer from the first node into the header
44 97 23 17
last
first
17
Queue implementation details
 With an array implementation:
 you can have both overflow and underflow
 you should set deleted elements to null
 With a linked-list implementation:
 you can have underflow
 overflow is a global out-of-memory condition
 there is no reason to set deleted elements to null
Queue and Multiprogramming
(1/2)
 Multiprogramming is a way of achieving a
limited form of parallelism
 It allows to run multiple tasks or
computational threads at the same time
 E.g., one thread can be responsible for
catching mouse clicks while others can be
responsible for moving parts of animation
around in a screen canvas
E:DSALcomp202 ULPweek2[1].ppt
Queue and Multiprogramming
(2/2)
 When we design a program or operating system
that uses multiple threads, we must disallow an
individual thread to monopolise the CPU, in order
to avoid application or applet hanging
 One of the solutions is to utilize a queue to
allocate the CPU time to the running threads in
the round-robin protocol.
Application of Queues: Buffers and
Scheduling
 Important use of queues is I/O scheduling
 Use buffers in memory to improve program
execution
 Buffer arranged
in FIFO
structure
E:Data StructuresHanif_Searchchapter08.ppt
Application of Queues: Buffers and
Scheduling
 Consider a keyboard buffer
 Acts as a queue
 But elements may be
removed from the back of
the queue with
backspace key
 A printer spool is a queue of print jobs
Application of Queues: Buffers and
Scheduling
 Queues used to
schedule tasks
within an operating
system
 Job moves from disk to ready queue
23
Deques
 A deque is a double-ended queue
 Insertions and deletions can occur at either end
 Implementation is similar to that for queues
 Deques are not heavily used
 You should know what a deque is, but we won’t
explore them much further
D:Data StructuresHanif_SearchQueues23-stacks-queues-deques.ppt
Application of Queues: Buffers and
Scheduling
 Also times when insertions, deletions must be
made from both ends
 This requires a double
ended queue
 Called a deque (pronounced "deck")
 Could also be considered a double ended stack (or
"dack")
D:Data StructuresHanif_Searchchapter08.ppt
Priority Queues
 Priority queues are queues in which items are ordered by priority
rather than temporally (i.e. order in which received).
 Any queue implementation then can be taken and modified to
acquire a priority queue.
 Instead of unconditionally adding to the back, the queue must be
scanned for the correct insertion point.
 An array implementation then would require shifting elements
 Hence a linked list implementation is preferred.
 A heap can be used as the underlying implementation of a priority
queue (to be discussed in heapsort algorithm).
E:Data StructuresHanif_SearchQueueschapter_05-queues.ppt
Application of Queues: Buffers and
Scheduling
 Ready queue may actually
be a priority queue … job may get to "cut the
line" based on its priority
D:Data StructuresHanif_Searchchapter08.ppt
Priority Queue
 Priority queues are often used in resource management, Event
simulation, and in the implementation of some algorithms (e.g.,
some graph algorithms, some backtracking algorithms).
 Several data structures can be used to implement priority queues.
Below is a comparison of some:
Dequeue MinFind MinEnqueueData structure
O(n)O(n)O(1)Unsorted List
O(1)O(1)O(n)Sorted List
O(log n)O(log n)O(log n)AVL Tree
O(log n)O(1)O(log n)MinHeap
D:Data StructuresICS202Lecture21.ppt+
D:Data StructuresHanif_SearchQueuesad5.ppt

More Related Content

What's hot

Data structure and algorithm All in One
Data structure and algorithm All in OneData structure and algorithm All in One
Data structure and algorithm All in Onejehan1987
 
Data structure and algorithm using java
Data structure and algorithm using javaData structure and algorithm using java
Data structure and algorithm using javaNarayan Sau
 
Data structures using C
Data structures using CData structures using C
Data structures using CPdr Patnaik
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsHoang Nguyen
 
DATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTESDATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTESAniruddha Paul
 
Introduction of data structure
Introduction of data structureIntroduction of data structure
Introduction of data structureeShikshak
 
هياكلبيانات
هياكلبياناتهياكلبيانات
هياكلبياناتRafal Edward
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1smruti sarangi
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#Shahzad
 
Data Structures- Part1 overview and review
Data Structures- Part1 overview and reviewData Structures- Part1 overview and review
Data Structures- Part1 overview and reviewAbdullah Al-hazmy
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for publiciqbalphy1
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm KristinaBorooah
 
Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting AlgorithmsAfaq Mansoor Khan
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like StructuresIntro C# Book
 
(Recursion)ads
(Recursion)ads(Recursion)ads
(Recursion)adsRavi Rao
 
Search algorithms master
Search algorithms masterSearch algorithms master
Search algorithms masterHossam Hassan
 

What's hot (20)

Data structures
Data structuresData structures
Data structures
 
Data structure and algorithm All in One
Data structure and algorithm All in OneData structure and algorithm All in One
Data structure and algorithm All in One
 
Data structure
Data structureData structure
Data structure
 
Data structure and algorithm using java
Data structure and algorithm using javaData structure and algorithm using java
Data structure and algorithm using java
 
Data structures using C
Data structures using CData structures using C
Data structures using C
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
DATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTESDATA STRUCTURE AND ALGORITHM FULL NOTES
DATA STRUCTURE AND ALGORITHM FULL NOTES
 
Introduction of data structure
Introduction of data structureIntroduction of data structure
Introduction of data structure
 
Data Structure
Data StructureData Structure
Data Structure
 
هياكلبيانات
هياكلبياناتهياكلبيانات
هياكلبيانات
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
Data Structures- Part1 overview and review
Data Structures- Part1 overview and reviewData Structures- Part1 overview and review
Data Structures- Part1 overview and review
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for public
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting Algorithms
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
 
(Recursion)ads
(Recursion)ads(Recursion)ads
(Recursion)ads
 
Big o notation
Big o notationBig o notation
Big o notation
 
Search algorithms master
Search algorithms masterSearch algorithms master
Search algorithms master
 

Similar to FIFO Queues and Priority Queues (20)

QUEUE in data-structure (classification, working procedure, Applications)
QUEUE in data-structure (classification, working procedure, Applications)QUEUE in data-structure (classification, working procedure, Applications)
QUEUE in data-structure (classification, working procedure, Applications)
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
2 b queues
2 b queues2 b queues
2 b queues
 
queue.pptx
queue.pptxqueue.pptx
queue.pptx
 
Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddu
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 
Queues
QueuesQueues
Queues
 
Queues
Queues Queues
Queues
 
Queue
QueueQueue
Queue
 
Unit 5 dsa QUEUE
Unit 5 dsa QUEUEUnit 5 dsa QUEUE
Unit 5 dsa QUEUE
 
Unit 4 queue
Unit   4 queueUnit   4 queue
Unit 4 queue
 
Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1
 
Queue
QueueQueue
Queue
 
Queue
QueueQueue
Queue
 
Stacks, Queues, Deques
Stacks, Queues, DequesStacks, Queues, Deques
Stacks, Queues, Deques
 
computer notes - Memory organization
computer notes - Memory organizationcomputer notes - Memory organization
computer notes - Memory organization
 
Queue
QueueQueue
Queue
 
Implementation of queue using singly and doubly linked list.
Implementation of queue using singly and doubly linked list.Implementation of queue using singly and doubly linked list.
Implementation of queue using singly and doubly linked list.
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
Queue
QueueQueue
Queue
 

More from Hanif Durad

More from Hanif Durad (17)

Chapter 26 aoa
Chapter 26 aoaChapter 26 aoa
Chapter 26 aoa
 
Chapter 25 aoa
Chapter 25 aoaChapter 25 aoa
Chapter 25 aoa
 
Chapter 24 aoa
Chapter 24 aoaChapter 24 aoa
Chapter 24 aoa
 
Chapter 23 aoa
Chapter 23 aoaChapter 23 aoa
Chapter 23 aoa
 
Chapter 12 ds
Chapter 12 dsChapter 12 ds
Chapter 12 ds
 
Chapter 9 ds
Chapter 9 dsChapter 9 ds
Chapter 9 ds
 
Chapter 8 ds
Chapter 8 dsChapter 8 ds
Chapter 8 ds
 
Chapter 2 ds
Chapter 2 dsChapter 2 ds
Chapter 2 ds
 
Chapter 5 pc
Chapter 5 pcChapter 5 pc
Chapter 5 pc
 
Chapter 4 pc
Chapter 4 pcChapter 4 pc
Chapter 4 pc
 
Chapter 3 pc
Chapter 3 pcChapter 3 pc
Chapter 3 pc
 
Chapter 2 pc
Chapter 2 pcChapter 2 pc
Chapter 2 pc
 
Chapter 1 pc
Chapter 1 pcChapter 1 pc
Chapter 1 pc
 
Chapter 6 pc
Chapter 6 pcChapter 6 pc
Chapter 6 pc
 
Collective Communications in MPI
 Collective Communications in MPI Collective Communications in MPI
Collective Communications in MPI
 
Point-to-Point Communicationsin MPI
Point-to-Point Communicationsin MPIPoint-to-Point Communicationsin MPI
Point-to-Point Communicationsin MPI
 
Introduction to MPI
Introduction to MPI Introduction to MPI
Introduction to MPI
 

Recently uploaded

URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 

Recently uploaded (20)

URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 

FIFO Queues and Priority Queues

  • 1. Chapter 7 QUEUES Dr. Muhammad Hanif Durad Department of Computer and Information Sciences Pakistan Institute Engineering and Applied Sciences hanif@pieas.edu.pk Some slides have bee adapted with thanks from some other lectures available on Internet. It made my life easier, as life is always miserable at PIEAS (Sir Muhammad Yusaf Kakakhil )
  • 2. Dr. Hanif Durad 2 Lecture Outline  Queues  Deques  Priority Queue
  • 3. Visualization of a Queue Dr. Hanif Durad 3 D:Data StructuresPRG DS CS11001L9-3.pdf
  • 4. 4 Queues, and Deques  A queue is a first in, first out (FIFO) data structure  Items are removed from a queue in the same order as they were inserted  A deque is a double-ended queue—items can be inserted and removed at either end D:Data StructuresHanif_SearchQueues23-stacks-queues-deques.ppt
  • 5. Queue Applications  Real life examples  Waiting in line  Waiting on hold for tech support  Applications related to Computer Science  Threads  Job scheduling (e.g. Round-Robin algorithm for CPU allocation) Dr. Hanif Durad 5 D:Data StructuresCSCE3110Queues.ppt
  • 6. 6 Queues (1/2)  A queue differs from a stack in that its insertion and removal routines follows the first-in-first-out (FIFO) principle.  Elements may be inserted at any time, but only the element which has been in the queue the longest may be removed.  Elements are inserted at the rear (enqueued) and removed from the front (dequeued) Front RearQueue D:Data StructuresHanif_SearchQueues ad5.ppt,P-23
  • 7. 7 Queues (2/2)  The queue supports three fundamental methods:  New():ADT – Creates an empty queue  Enqueue(S:ADT, o:element):ADT - Inserts object o at the rear of the queue  Dequeue(S:ADT):ADT - Removes the object from the front of the queue; an error occurs if the queue is empty  Front(S:ADT):element - Returns, but does not remove, the front element; an error occurs if the queue is empty
  • 8. 8 Array implementation of queues  A queue is a first in, first out (FIFO) data structure  This is accomplished by inserting at one end (the rear) and deleting from the other (the front)  To insert: put new element in location 4, and set rear to 4  To delete: take element from location 0, and set front to 1 17 23 97 44 0 1 2 3 4 5 6 7 myQueue: rear = 3front = 0 D:Data StructuresHanif_SearchQueues23-stacks-queues-deques.ppt
  • 9. 9 Array implementation of queues  Notice how the array contents “crawl” to the right as elements are inserted and deleted  This will be a problem after a while! 17 23 97 44 333After insertion: 23 97 44 333After deletion: rear = 4front = 1 17 23 97 44Initial queue: rear = 3front = 0
  • 10. 10 Circular arrays  We can treat the array holding the queue elements as circular (joined at the ends) 44 55 11 22 33 0 1 2 3 4 5 6 7 myQueue: rear = 1 front = 5  Elements were added to this queue in the order 11, 22, 33, 44, 55, and will be removed in the same order  Use: front = (front + 1) % myQueue.length; and: rear = (rear + 1) % myQueue.length;
  • 11. 11 Full and empty queues  If the queue were to become completely full, it would look like this:  If we were then to remove all eight elements, making the queue completely empty, it would look like this: 44 55 66 77 88 11 22 33 0 1 2 3 4 5 6 7 myQueue: rear = 4 front = 5 0 1 2 3 4 5 6 7 myQueue: rear = 4 front = 5 This is a problem!
  • 12. 12 Full and empty queues: solutions  Solution #1: Keep an additional variable  Solution #2: (Slightly more efficient) Keep a gap between elements: consider the queue full when it has n-1 elements 44 55 66 77 88 11 22 33 0 1 2 3 4 5 6 7 myQueue: rear = 4 front = 5count = 8 44 55 66 77 11 22 33 0 1 2 3 4 5 6 7 myQueue: rear = 3 front = 5
  • 13. Queue Implementation using Linked List  Basic idea:  Create a linked list to which items would be added to one end and deleted from the other end.  Two pointers will be maintained:  One pointing to the beginning of the list (point fromwhere elements will be deleted). <Front>  Another pointing to the end of the list (point where new elements will be inserted). <Rear> 13 D:Data StructuresPRG DS CS11001L9-3.pdf
  • 14. 14 Linked-list implementation of queues  In a queue, insertions occur at one end, deletions at the other end  Operations at the front of a singly-linked list (SLL) are O(1), but at the other end they are O(n)  Because you have to find the last element each time  BUT: there is a simple way to use a singly-linked list to implement both insertions and deletions in O(1) time  You always need a pointer to the first thing in the list  You can keep an additional pointer to the last thing in the list
  • 15. 15 Enqueueing a node 17 Node to be enqueued To enqueue (add) a node: Find the current last node Change it to point to the new last node Change the last pointer in the list header 2344 last first 97
  • 16. 16 Dequeueing a node  To dequeue (remove) a node:  Copy the pointer from the first node into the header 44 97 23 17 last first
  • 17. 17 Queue implementation details  With an array implementation:  you can have both overflow and underflow  you should set deleted elements to null  With a linked-list implementation:  you can have underflow  overflow is a global out-of-memory condition  there is no reason to set deleted elements to null
  • 18. Queue and Multiprogramming (1/2)  Multiprogramming is a way of achieving a limited form of parallelism  It allows to run multiple tasks or computational threads at the same time  E.g., one thread can be responsible for catching mouse clicks while others can be responsible for moving parts of animation around in a screen canvas E:DSALcomp202 ULPweek2[1].ppt
  • 19. Queue and Multiprogramming (2/2)  When we design a program or operating system that uses multiple threads, we must disallow an individual thread to monopolise the CPU, in order to avoid application or applet hanging  One of the solutions is to utilize a queue to allocate the CPU time to the running threads in the round-robin protocol.
  • 20. Application of Queues: Buffers and Scheduling  Important use of queues is I/O scheduling  Use buffers in memory to improve program execution  Buffer arranged in FIFO structure E:Data StructuresHanif_Searchchapter08.ppt
  • 21. Application of Queues: Buffers and Scheduling  Consider a keyboard buffer  Acts as a queue  But elements may be removed from the back of the queue with backspace key  A printer spool is a queue of print jobs
  • 22. Application of Queues: Buffers and Scheduling  Queues used to schedule tasks within an operating system  Job moves from disk to ready queue
  • 23. 23 Deques  A deque is a double-ended queue  Insertions and deletions can occur at either end  Implementation is similar to that for queues  Deques are not heavily used  You should know what a deque is, but we won’t explore them much further D:Data StructuresHanif_SearchQueues23-stacks-queues-deques.ppt
  • 24. Application of Queues: Buffers and Scheduling  Also times when insertions, deletions must be made from both ends  This requires a double ended queue  Called a deque (pronounced "deck")  Could also be considered a double ended stack (or "dack") D:Data StructuresHanif_Searchchapter08.ppt
  • 25. Priority Queues  Priority queues are queues in which items are ordered by priority rather than temporally (i.e. order in which received).  Any queue implementation then can be taken and modified to acquire a priority queue.  Instead of unconditionally adding to the back, the queue must be scanned for the correct insertion point.  An array implementation then would require shifting elements  Hence a linked list implementation is preferred.  A heap can be used as the underlying implementation of a priority queue (to be discussed in heapsort algorithm). E:Data StructuresHanif_SearchQueueschapter_05-queues.ppt
  • 26. Application of Queues: Buffers and Scheduling  Ready queue may actually be a priority queue … job may get to "cut the line" based on its priority D:Data StructuresHanif_Searchchapter08.ppt
  • 27. Priority Queue  Priority queues are often used in resource management, Event simulation, and in the implementation of some algorithms (e.g., some graph algorithms, some backtracking algorithms).  Several data structures can be used to implement priority queues. Below is a comparison of some: Dequeue MinFind MinEnqueueData structure O(n)O(n)O(1)Unsorted List O(1)O(1)O(n)Sorted List O(log n)O(log n)O(log n)AVL Tree O(log n)O(1)O(log n)MinHeap D:Data StructuresICS202Lecture21.ppt+ D:Data StructuresHanif_SearchQueuesad5.ppt