SlideShare a Scribd company logo
Data Structures and Algorithms in Java 1/21
2. Stack and Queue
Part 2: Queue
Data Structures and Algorithms in Java 2/21
Queues
Objectives
• Queues
• Priority Queues
• Queue interface in java.util
Data Structures and Algorithms in Java 3/21
What is a queue?
3
• A queue is a waiting line that grows by adding
elements to its end and shrinks by taking
elements from its front
• A queue is a structure in which both ends are
used:
– One for adding new elements
– One for removing them
• A queue is an FIFO structure: First In/First Out
Data Structures and Algorithms in Java 4/21
Operations on a queue
4
• The following operations are needed to properly manage a
queue:
– clear() — Clear the queue
– isEmpty() — Check to see if the queue is empty
– enqueue(el) — Put the element el at the end of the queue
– dequeue() — Take the first element from the queue
– front() — Return the first element in the queue without
removing it
• Exceptions
– Attempting the execution of dequeue or front on an empty
queue throws an EmptyQueueException
sometimes the peek() is named instead of front().
Data Structures and Algorithms in Java 5/21
5
Queue example
Operation Output Q
enqueue(5) – (5)
enqueue(3) – (5, 3)
dequeue() 5 (3)
enqueue(7) – (3, 7)
dequeue() 3 (7)
front() 7 (7)
dequeue() 7 ()
dequeue() “error” ()
isEmpty() true ()
enqueue(9) – (9)
enqueue(7) – (9, 7)
size() 2 (9, 7)
enqueue(3) – (9, 7, 3)
enqueue(5) – (9, 7, 3, 5)
dequeue() 9 (7, 3, 5)
Data Structures and Algorithms in Java 6/21
Applications of Queues
• Direct applications
– Waiting lists, bureaucracy
– Access to shared resources (e.g., printer)
– Multiprogramming
• Indirect applications
– Auxiliary data structure for algorithms
– Component of other data structures
Data Structures and Algorithms in Java 7/21
Application: Round Robin Schedulers
We can implement a round robin scheduler using a queue, Q,
by repeatedly performing the following steps:
1. e = Q.dequeue()
2. Service element e
3. Q.enqueue(e)
The Queue
Shared
Service
1. Deque the
next element
3. Enqueue the
serviced element
2. Service the
next element
Round-robin (RR) is one of the simplest scheduling algorithms for processes in an
operating system, which assigns time slices to each process in equal portions and in
circular order, handling all processes without priority. Round-robin scheduling is both
simple and easy to implement, and starvation-free. Round-robin scheduling can also be
applied to other scheduling problems, such as data packet scheduling in computer
networks.
The name of the algorithm comes from the round-robin principle known from other fields,
where each person takes an equal share of something in turn
Round Robin Schedulers
Data Structures and Algorithms in Java 8/21
Array-based Queue - 1
• Use an array of size N in a circular fashion
• Two variables keep track of the first and last
f index of the front element
l index of the last element
Q
0 1 2 l
f
normal configuration
Q
0 1 2 f
l
wrapped-around configuration
Array-based Queue
Data Structures and Algorithms in Java 9/21
Array-based Queue - 2
Array-based Queue in detail
Data Structures and Algorithms in Java 10/21
Array implementation of a queue - 1
10
class ArrayQueue
{ protected Object [] a;
protected int max;
protected int first, last;
public ArrayQueue()
{ this(10);
}
public ArrayQueue(int max1)
{ max = max1;
a = new Object[max];
first = last = -1;
}
public boolean isEmpty()
{ return(first==-1);}
public boolean isFull()
{ return((first == 0 &&
last == max-1) || first == last+1);
}
private boolean grow()
{ int i,j;
int max1 = max + max/2;
Object [] a1 = new Object[max1];
if(a1 == null) return(false);
if(last>=first)
for(i=first;i<=last;i++) a1[i-first]=a[i];
else
{ for(i=first;i<max;i++) a1[i-first]=a[i];
i = max-first;
for(j=0;j<=last;j++) a1[i+j]=a[j];
}
a = a1;
first = 0;
last = max-1;
max = max1;
return(true);
}
Data Structures and Algorithms in Java 11/21
Array implementation of a queue - 2
11
void enqueue(Object x)
{ if(isFull() && !grow()) return;
if(last == max-1 || last == -1)
{ a[0] = x; last=0;
if(first==-1) first = 0;
}
else a[++last] = x;
}
Object front() throws Exception
{ if(isEmpty()) throw new Exception();
return(a[first]);
}
public Object dequeue() throws Exception
{ if(isEmpty()) throw new Exception();
Object x = a[first];
if(first == last) // only one element
{first = last = -1;}
else if(first==max-1)
first = 0;
else
first++;
return(x);
}
Data Structures and Algorithms in Java 12/21
Linked list implementation of a queue
12
class Node
{ public Object info;
public Node next;
public Node(Object x, Node p)
{ info=x; next=p; }
public Node(Object x)
{ this(x,null); }
};
class MyQueue
{ protected Node head,tail;
public MyQueue()
{ head = tail = null; }
public boolean isEmpty()
{ return(head==null);}
Object front() throws Exception
{ if(isEmpty()) throw new Exception();
return(head.info);
}
public Object dequeue() throws Exception
{ if(isEmpty()) throw new Exception();
Object x = head.info;
head=head.next;
if(head==null) tail=null;
return(x);
}
void enqueue(Object x)
{ if(isEmpty())
head = tail = new Node(x);
else
{ tail.next = new Node(x);
tail = tail.next;
}
}
Data Structures and Algorithms in Java 13/21
A Circular Queue
In previous chapter , we implemented a circularly linked list class that supports
all behaviors of a singly linked list, and an additional rotate( ) method that
efficiently moves the first element to the end of the list. We can generalize the
Queue interface to define a new CircularQueue interface with such a behavior, as
shown below:
public interface CircularQueue extends Queue {
/*Rotates the front element of the queue to the back of the queue.
This does nothing if the queue is empty.*/
void rotate( );
}
A Java interface, CircularQueue, that extends the Queue ADT with a new rotate( )
method. This interface can easily be implemented by adapting the
CircularlyLinkedList class to produce a new LinkedCircularQueue class. This class
has an advantage over the traditional LinkedQueue, because a call to Q.rotate( )
is implemented more efficiently than the combination of calls,
Q.enqueue(Q.dequeue( )), because no nodes are created, destroyed, or relinked
by the implementation of a rotate operation on a circularly linked list.
A circular queue is an excellent abstraction for applications in which elements are
cyclically arranged, such as for multiplayer, turn-based games, or round-robin
scheduling of computing processes.
Data Structures and Algorithms in Java 14/21
Queue Interface in Java - 1
• Java interface
corresponding to our
Queue ADT
• Requires the
definition of class
EmptyQueueException
• No corresponding
built-in Java class
public interface Queue {
public int size();
public boolean isEmpty();
public Object front()
throws EmptyQueueException;
public void enqueue(Object o);
public Object dequeue()
throws EmptyQueueException;
}
Data Structures and Algorithms in Java 15/21
Double-Ended Queues (Deque) - 1
15
We next consider a queue-like data structure that supports
insertion and deletion at both the front and the back of the queue.
Such a structure is called a doubleended queue, or deque, which
is usually pronounced “deck” to avoid confusion with the dequeue
method of the regular queue ADT, which is pronounced like the
abbreviation “D.Q.”
The deque abstract data type is more general than both the stack
and the queue ADTs. The extra generality can be useful in some
applications. For example, we described a restaurant using a
queue to maintain a waitlist. Occasionally, the first person might be
removed from the queue only to find that a table was not available;
typically, the restaurant will reinsert the person at the first position
in the queue. It may also be that a customer at the end of the
queue may grow impatient and leave the restaurant.
Data Structures and Algorithms in Java 16/21
Double-Ended Queues (Deque) - 2
16
The deque abstract data type is richer than both the stack and the queue
ADTs. To provide a symmetrical abstraction, the deque ADT is defined to
support the following update methods:
addFirst(e): Insert a new element e at the front of the deque.
addLast(e): Insert a new element e at the back of the deque.
removeFirst( ): Remove and return the first element of the deque (or null if
the deque is empty).
removeLast( ): Remove and return the last element of the deque (or null if
the deque is empty).
Additionally, the deque ADT will include the following accessors:
first( ): Returns the first element of the deque, without removing it (or null if
the deque is empty).
last( ): Returns the last element of the deque, without removing it (or null if
the deque is empty).
size( ): Returns the number of elements in the deque.
isEmpty( ): Returns a boolean indicating whether the deque is empty.
Data Structures and Algorithms in Java 17/21
Priority Queues
17
• A priority queue can be assigned to enable a
particular process, or event, to be executed
out of sequence without affecting overall
system operation
• FIFO rule is broken in these situations
• In priority queues, elements are dequeued
according to their priority and their current
queue position
Data Structures and Algorithms in Java 18/21
Array implementation of a priority queue - 1
18
class PriorityQueue
{ protected float [] a; int top, max;
public PriorityQueue()
{ this(50);
}
public PriorityQueue(int max1)
{ max = max1;
a = new float[max];
top = -1;
}
protected boolean grow()
{ int max1 = max + max/2;
float [] a1 = new float[max1];
if(a1 == null) return(false);
for(int i =0; i<=top; i++)
a1[i] = a[i];
a = a1;
return(true);
}
public boolean isEmpty()
{ return(top==-1);}
public boolean isFull()
{ return(top==max-1);}
public void clear()
{ top=-1;}
public void enqueue(float x)
{ if(isFull() && !grow()) return;
if(top==-1)
{ a[0] = x; top = 0;
return;
}
int i = top;
while(i>=0 && x<a[i])
{ a[i+1] = a[i];
i--;
}
a[i+1] = x; top++;
}
Data Structures and Algorithms in Java 19/21
Array implementation of a priority queue - 2
19
public float front()
{ assert(!isEmpty());
return(a[top]);
}
public float dequeue()
{assert(!isEmpty());
float x = a[top];
top--;
return(x);
}
Data Structures and Algorithms in Java 20/21
Summary
20
• A queue is a waiting line that grows by adding elements to its
end and shrinks by taking elements from its front.
• A queue is an FIFO structure: first in/first out.
• In queuing theory, various scenarios are analyzed and models
are built that use queues for processing requests or
other information in a predetermined sequence (order).
• A priority queue can be assigned to enable a particular
process, or event, to be executed out of sequence without
affecting overall system operation.
• In priority queues, elements are dequeued according to their
priority and their current
queue position.
Data Structures and Algorithms in Java 21/21
Reading at home
Text book: Data Structures and Algorithms in Java
• 6.2 Queues - 238
• 6.3 Double-Ended Queues (Deque) - 248
• 9.1 The Priority Queue Abstract Data Type - 360

More Related Content

What's hot

stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for public
iqbalphy1
 
Chapter 4 ds
Chapter 4 dsChapter 4 ds
Chapter 4 ds
Hanif Durad
 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 ds
Hanif Durad
 
هياكلبيانات
هياكلبياناتهياكلبيانات
هياكلبياناتRafal Edward
 
Chapter 6 ds
Chapter 6 dsChapter 6 ds
Chapter 6 ds
Hanif Durad
 
Chapter 7 ds
Chapter 7 dsChapter 7 ds
Chapter 7 ds
Hanif Durad
 
3 recursion
3 recursion3 recursion
3 recursion
Nguync91368
 
Searching Algorithms
Searching AlgorithmsSearching Algorithms
Searching Algorithms
Afaq Mansoor Khan
 
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
jehan1987
 
Data structure
Data structureData structure
Data structure
Muhammad Farhan
 
358 33 powerpoint-slides_8-linked-lists_chapter-8
358 33 powerpoint-slides_8-linked-lists_chapter-8358 33 powerpoint-slides_8-linked-lists_chapter-8
358 33 powerpoint-slides_8-linked-lists_chapter-8
sumitbardhan
 
Programming in java - Concepts- Operators- Control statements-Expressions
Programming in java - Concepts- Operators- Control statements-ExpressionsProgramming in java - Concepts- Operators- Control statements-Expressions
Programming in java - Concepts- Operators- Control statements-Expressions
LovelitJose
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
Shahzad
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Moniruzzaman _
 
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its Fundamentals
Hitesh Mohapatra
 
Introduction of data structure
Introduction of data structureIntroduction of data structure
Introduction of data structureeShikshak
 
Recursion Pattern Analysis and Feedback
Recursion Pattern Analysis and FeedbackRecursion Pattern Analysis and Feedback
Recursion Pattern Analysis and Feedback
Sander Mak (@Sander_Mak)
 
Datastructure
DatastructureDatastructure
Datastructure
Griffinder VinHai
 

What's hot (20)

stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for public
 
Chapter 4 ds
Chapter 4 dsChapter 4 ds
Chapter 4 ds
 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 ds
 
هياكلبيانات
هياكلبياناتهياكلبيانات
هياكلبيانات
 
Chapter 6 ds
Chapter 6 dsChapter 6 ds
Chapter 6 ds
 
Chapter 7 ds
Chapter 7 dsChapter 7 ds
Chapter 7 ds
 
3 recursion
3 recursion3 recursion
3 recursion
 
Searching Algorithms
Searching AlgorithmsSearching Algorithms
Searching Algorithms
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
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
 
LectureNotes-03-DSA
LectureNotes-03-DSALectureNotes-03-DSA
LectureNotes-03-DSA
 
Data structure
Data structureData structure
Data structure
 
358 33 powerpoint-slides_8-linked-lists_chapter-8
358 33 powerpoint-slides_8-linked-lists_chapter-8358 33 powerpoint-slides_8-linked-lists_chapter-8
358 33 powerpoint-slides_8-linked-lists_chapter-8
 
Programming in java - Concepts- Operators- Control statements-Expressions
Programming in java - Concepts- Operators- Control statements-ExpressionsProgramming in java - Concepts- Operators- Control statements-Expressions
Programming in java - Concepts- Operators- Control statements-Expressions
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its Fundamentals
 
Introduction of data structure
Introduction of data structureIntroduction of data structure
Introduction of data structure
 
Recursion Pattern Analysis and Feedback
Recursion Pattern Analysis and FeedbackRecursion Pattern Analysis and Feedback
Recursion Pattern Analysis and Feedback
 
Datastructure
DatastructureDatastructure
Datastructure
 

Similar to 2 b queues

queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
RAtna29
 
Unit 4 queue
Unit   4 queueUnit   4 queue
Unit 4 queue
Dabbal Singh Mahara
 
basics of queues
basics of queuesbasics of queues
basics of queues
sirmanohar
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
Rajkiran Nadar
 
Queue
QueueQueue
Queue
QueueQueue
Data structure.ppt
Data structure.pptData structure.ppt
Data structure.ppt
SajalFayyaz
 
In java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdfIn java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdf
aromalcom
 
Data structures
Data structuresData structures
Data structures
naveeth babu
 
DS UNIT2QUEUES.pptx
DS UNIT2QUEUES.pptxDS UNIT2QUEUES.pptx
DS UNIT2QUEUES.pptx
VeerannaKotagi1
 
Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.ppt
OliverKane3
 
Fundamentals of Data Structure and Queues
Fundamentals of Data Structure and QueuesFundamentals of Data Structure and Queues
Fundamentals of Data Structure and Queues
Bogiri Nagaraju
 
Data Structure Using C
Data Structure Using CData Structure Using C
Data Structure Using C
cpjcollege
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
•sreejith •sree
 
computer notes - Priority queue
computer notes -  Priority queuecomputer notes -  Priority queue
computer notes - Priority queue
ecomputernotes
 
Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1
blessyboban92
 
Queue
QueueQueue
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
GauravPatil318
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
Sriram Raj
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
Zidny Nafan
 

Similar to 2 b queues (20)

queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 
Unit 4 queue
Unit   4 queueUnit   4 queue
Unit 4 queue
 
basics of queues
basics of queuesbasics of queues
basics of queues
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
Queue
QueueQueue
Queue
 
Queue
QueueQueue
Queue
 
Data structure.ppt
Data structure.pptData structure.ppt
Data structure.ppt
 
In java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdfIn java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdf
 
Data structures
Data structuresData structures
Data structures
 
DS UNIT2QUEUES.pptx
DS UNIT2QUEUES.pptxDS UNIT2QUEUES.pptx
DS UNIT2QUEUES.pptx
 
Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.ppt
 
Fundamentals of Data Structure and Queues
Fundamentals of Data Structure and QueuesFundamentals of Data Structure and Queues
Fundamentals of Data Structure and Queues
 
Data Structure Using C
Data Structure Using CData Structure Using C
Data Structure Using C
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
 
computer notes - Priority queue
computer notes -  Priority queuecomputer notes -  Priority queue
computer notes - Priority 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
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 

Recently uploaded

GBSN - Microbiology (Lab 4) Culture Media
GBSN - Microbiology (Lab 4) Culture MediaGBSN - Microbiology (Lab 4) Culture Media
GBSN - Microbiology (Lab 4) Culture Media
Areesha Ahmad
 
Citrus Greening Disease and its Management
Citrus Greening Disease and its ManagementCitrus Greening Disease and its Management
Citrus Greening Disease and its Management
subedisuryaofficial
 
in vitro propagation of plants lecture note.pptx
in vitro propagation of plants lecture note.pptxin vitro propagation of plants lecture note.pptx
in vitro propagation of plants lecture note.pptx
yusufzako14
 
GBSN - Biochemistry (Unit 5) Chemistry of Lipids
GBSN - Biochemistry (Unit 5) Chemistry of LipidsGBSN - Biochemistry (Unit 5) Chemistry of Lipids
GBSN - Biochemistry (Unit 5) Chemistry of Lipids
Areesha Ahmad
 
GBSN- Microbiology (Lab 3) Gram Staining
GBSN- Microbiology (Lab 3) Gram StainingGBSN- Microbiology (Lab 3) Gram Staining
GBSN- Microbiology (Lab 3) Gram Staining
Areesha Ahmad
 
Structures and textures of metamorphic rocks
Structures and textures of metamorphic rocksStructures and textures of metamorphic rocks
Structures and textures of metamorphic rocks
kumarmathi863
 
Mammalian Pineal Body Structure and Also Functions
Mammalian Pineal Body Structure and Also FunctionsMammalian Pineal Body Structure and Also Functions
Mammalian Pineal Body Structure and Also Functions
YOGESH DOGRA
 
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Sérgio Sacani
 
Hemostasis_importance& clinical significance.pptx
Hemostasis_importance& clinical significance.pptxHemostasis_importance& clinical significance.pptx
Hemostasis_importance& clinical significance.pptx
muralinath2
 
erythropoiesis-I_mechanism& clinical significance.pptx
erythropoiesis-I_mechanism& clinical significance.pptxerythropoiesis-I_mechanism& clinical significance.pptx
erythropoiesis-I_mechanism& clinical significance.pptx
muralinath2
 
general properties of oerganologametal.ppt
general properties of oerganologametal.pptgeneral properties of oerganologametal.ppt
general properties of oerganologametal.ppt
IqrimaNabilatulhusni
 
SCHIZOPHRENIA Disorder/ Brain Disorder.pdf
SCHIZOPHRENIA Disorder/ Brain Disorder.pdfSCHIZOPHRENIA Disorder/ Brain Disorder.pdf
SCHIZOPHRENIA Disorder/ Brain Disorder.pdf
SELF-EXPLANATORY
 
THE IMPORTANCE OF MARTIAN ATMOSPHERE SAMPLE RETURN.
THE IMPORTANCE OF MARTIAN ATMOSPHERE SAMPLE RETURN.THE IMPORTANCE OF MARTIAN ATMOSPHERE SAMPLE RETURN.
THE IMPORTANCE OF MARTIAN ATMOSPHERE SAMPLE RETURN.
Sérgio Sacani
 
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
Scintica Instrumentation
 
Unveiling the Energy Potential of Marshmallow Deposits.pdf
Unveiling the Energy Potential of Marshmallow Deposits.pdfUnveiling the Energy Potential of Marshmallow Deposits.pdf
Unveiling the Energy Potential of Marshmallow Deposits.pdf
Erdal Coalmaker
 
Richard's aventures in two entangled wonderlands
Richard's aventures in two entangled wonderlandsRichard's aventures in two entangled wonderlands
Richard's aventures in two entangled wonderlands
Richard Gill
 
Multi-source connectivity as the driver of solar wind variability in the heli...
Multi-source connectivity as the driver of solar wind variability in the heli...Multi-source connectivity as the driver of solar wind variability in the heli...
Multi-source connectivity as the driver of solar wind variability in the heli...
Sérgio Sacani
 
Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...
Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...
Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...
muralinath2
 
EY - Supply Chain Services 2018_template.pptx
EY - Supply Chain Services 2018_template.pptxEY - Supply Chain Services 2018_template.pptx
EY - Supply Chain Services 2018_template.pptx
AlguinaldoKong
 
platelets_clotting_biogenesis.clot retractionpptx
platelets_clotting_biogenesis.clot retractionpptxplatelets_clotting_biogenesis.clot retractionpptx
platelets_clotting_biogenesis.clot retractionpptx
muralinath2
 

Recently uploaded (20)

GBSN - Microbiology (Lab 4) Culture Media
GBSN - Microbiology (Lab 4) Culture MediaGBSN - Microbiology (Lab 4) Culture Media
GBSN - Microbiology (Lab 4) Culture Media
 
Citrus Greening Disease and its Management
Citrus Greening Disease and its ManagementCitrus Greening Disease and its Management
Citrus Greening Disease and its Management
 
in vitro propagation of plants lecture note.pptx
in vitro propagation of plants lecture note.pptxin vitro propagation of plants lecture note.pptx
in vitro propagation of plants lecture note.pptx
 
GBSN - Biochemistry (Unit 5) Chemistry of Lipids
GBSN - Biochemistry (Unit 5) Chemistry of LipidsGBSN - Biochemistry (Unit 5) Chemistry of Lipids
GBSN - Biochemistry (Unit 5) Chemistry of Lipids
 
GBSN- Microbiology (Lab 3) Gram Staining
GBSN- Microbiology (Lab 3) Gram StainingGBSN- Microbiology (Lab 3) Gram Staining
GBSN- Microbiology (Lab 3) Gram Staining
 
Structures and textures of metamorphic rocks
Structures and textures of metamorphic rocksStructures and textures of metamorphic rocks
Structures and textures of metamorphic rocks
 
Mammalian Pineal Body Structure and Also Functions
Mammalian Pineal Body Structure and Also FunctionsMammalian Pineal Body Structure and Also Functions
Mammalian Pineal Body Structure and Also Functions
 
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
Earliest Galaxies in the JADES Origins Field: Luminosity Function and Cosmic ...
 
Hemostasis_importance& clinical significance.pptx
Hemostasis_importance& clinical significance.pptxHemostasis_importance& clinical significance.pptx
Hemostasis_importance& clinical significance.pptx
 
erythropoiesis-I_mechanism& clinical significance.pptx
erythropoiesis-I_mechanism& clinical significance.pptxerythropoiesis-I_mechanism& clinical significance.pptx
erythropoiesis-I_mechanism& clinical significance.pptx
 
general properties of oerganologametal.ppt
general properties of oerganologametal.pptgeneral properties of oerganologametal.ppt
general properties of oerganologametal.ppt
 
SCHIZOPHRENIA Disorder/ Brain Disorder.pdf
SCHIZOPHRENIA Disorder/ Brain Disorder.pdfSCHIZOPHRENIA Disorder/ Brain Disorder.pdf
SCHIZOPHRENIA Disorder/ Brain Disorder.pdf
 
THE IMPORTANCE OF MARTIAN ATMOSPHERE SAMPLE RETURN.
THE IMPORTANCE OF MARTIAN ATMOSPHERE SAMPLE RETURN.THE IMPORTANCE OF MARTIAN ATMOSPHERE SAMPLE RETURN.
THE IMPORTANCE OF MARTIAN ATMOSPHERE SAMPLE RETURN.
 
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
(May 29th, 2024) Advancements in Intravital Microscopy- Insights for Preclini...
 
Unveiling the Energy Potential of Marshmallow Deposits.pdf
Unveiling the Energy Potential of Marshmallow Deposits.pdfUnveiling the Energy Potential of Marshmallow Deposits.pdf
Unveiling the Energy Potential of Marshmallow Deposits.pdf
 
Richard's aventures in two entangled wonderlands
Richard's aventures in two entangled wonderlandsRichard's aventures in two entangled wonderlands
Richard's aventures in two entangled wonderlands
 
Multi-source connectivity as the driver of solar wind variability in the heli...
Multi-source connectivity as the driver of solar wind variability in the heli...Multi-source connectivity as the driver of solar wind variability in the heli...
Multi-source connectivity as the driver of solar wind variability in the heli...
 
Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...
Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...
Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...
 
EY - Supply Chain Services 2018_template.pptx
EY - Supply Chain Services 2018_template.pptxEY - Supply Chain Services 2018_template.pptx
EY - Supply Chain Services 2018_template.pptx
 
platelets_clotting_biogenesis.clot retractionpptx
platelets_clotting_biogenesis.clot retractionpptxplatelets_clotting_biogenesis.clot retractionpptx
platelets_clotting_biogenesis.clot retractionpptx
 

2 b queues

  • 1. Data Structures and Algorithms in Java 1/21 2. Stack and Queue Part 2: Queue
  • 2. Data Structures and Algorithms in Java 2/21 Queues Objectives • Queues • Priority Queues • Queue interface in java.util
  • 3. Data Structures and Algorithms in Java 3/21 What is a queue? 3 • A queue is a waiting line that grows by adding elements to its end and shrinks by taking elements from its front • A queue is a structure in which both ends are used: – One for adding new elements – One for removing them • A queue is an FIFO structure: First In/First Out
  • 4. Data Structures and Algorithms in Java 4/21 Operations on a queue 4 • The following operations are needed to properly manage a queue: – clear() — Clear the queue – isEmpty() — Check to see if the queue is empty – enqueue(el) — Put the element el at the end of the queue – dequeue() — Take the first element from the queue – front() — Return the first element in the queue without removing it • Exceptions – Attempting the execution of dequeue or front on an empty queue throws an EmptyQueueException sometimes the peek() is named instead of front().
  • 5. Data Structures and Algorithms in Java 5/21 5 Queue example Operation Output Q enqueue(5) – (5) enqueue(3) – (5, 3) dequeue() 5 (3) enqueue(7) – (3, 7) dequeue() 3 (7) front() 7 (7) dequeue() 7 () dequeue() “error” () isEmpty() true () enqueue(9) – (9) enqueue(7) – (9, 7) size() 2 (9, 7) enqueue(3) – (9, 7, 3) enqueue(5) – (9, 7, 3, 5) dequeue() 9 (7, 3, 5)
  • 6. Data Structures and Algorithms in Java 6/21 Applications of Queues • Direct applications – Waiting lists, bureaucracy – Access to shared resources (e.g., printer) – Multiprogramming • Indirect applications – Auxiliary data structure for algorithms – Component of other data structures
  • 7. Data Structures and Algorithms in Java 7/21 Application: Round Robin Schedulers We can implement a round robin scheduler using a queue, Q, by repeatedly performing the following steps: 1. e = Q.dequeue() 2. Service element e 3. Q.enqueue(e) The Queue Shared Service 1. Deque the next element 3. Enqueue the serviced element 2. Service the next element Round-robin (RR) is one of the simplest scheduling algorithms for processes in an operating system, which assigns time slices to each process in equal portions and in circular order, handling all processes without priority. Round-robin scheduling is both simple and easy to implement, and starvation-free. Round-robin scheduling can also be applied to other scheduling problems, such as data packet scheduling in computer networks. The name of the algorithm comes from the round-robin principle known from other fields, where each person takes an equal share of something in turn Round Robin Schedulers
  • 8. Data Structures and Algorithms in Java 8/21 Array-based Queue - 1 • Use an array of size N in a circular fashion • Two variables keep track of the first and last f index of the front element l index of the last element Q 0 1 2 l f normal configuration Q 0 1 2 f l wrapped-around configuration Array-based Queue
  • 9. Data Structures and Algorithms in Java 9/21 Array-based Queue - 2 Array-based Queue in detail
  • 10. Data Structures and Algorithms in Java 10/21 Array implementation of a queue - 1 10 class ArrayQueue { protected Object [] a; protected int max; protected int first, last; public ArrayQueue() { this(10); } public ArrayQueue(int max1) { max = max1; a = new Object[max]; first = last = -1; } public boolean isEmpty() { return(first==-1);} public boolean isFull() { return((first == 0 && last == max-1) || first == last+1); } private boolean grow() { int i,j; int max1 = max + max/2; Object [] a1 = new Object[max1]; if(a1 == null) return(false); if(last>=first) for(i=first;i<=last;i++) a1[i-first]=a[i]; else { for(i=first;i<max;i++) a1[i-first]=a[i]; i = max-first; for(j=0;j<=last;j++) a1[i+j]=a[j]; } a = a1; first = 0; last = max-1; max = max1; return(true); }
  • 11. Data Structures and Algorithms in Java 11/21 Array implementation of a queue - 2 11 void enqueue(Object x) { if(isFull() && !grow()) return; if(last == max-1 || last == -1) { a[0] = x; last=0; if(first==-1) first = 0; } else a[++last] = x; } Object front() throws Exception { if(isEmpty()) throw new Exception(); return(a[first]); } public Object dequeue() throws Exception { if(isEmpty()) throw new Exception(); Object x = a[first]; if(first == last) // only one element {first = last = -1;} else if(first==max-1) first = 0; else first++; return(x); }
  • 12. Data Structures and Algorithms in Java 12/21 Linked list implementation of a queue 12 class Node { public Object info; public Node next; public Node(Object x, Node p) { info=x; next=p; } public Node(Object x) { this(x,null); } }; class MyQueue { protected Node head,tail; public MyQueue() { head = tail = null; } public boolean isEmpty() { return(head==null);} Object front() throws Exception { if(isEmpty()) throw new Exception(); return(head.info); } public Object dequeue() throws Exception { if(isEmpty()) throw new Exception(); Object x = head.info; head=head.next; if(head==null) tail=null; return(x); } void enqueue(Object x) { if(isEmpty()) head = tail = new Node(x); else { tail.next = new Node(x); tail = tail.next; } }
  • 13. Data Structures and Algorithms in Java 13/21 A Circular Queue In previous chapter , we implemented a circularly linked list class that supports all behaviors of a singly linked list, and an additional rotate( ) method that efficiently moves the first element to the end of the list. We can generalize the Queue interface to define a new CircularQueue interface with such a behavior, as shown below: public interface CircularQueue extends Queue { /*Rotates the front element of the queue to the back of the queue. This does nothing if the queue is empty.*/ void rotate( ); } A Java interface, CircularQueue, that extends the Queue ADT with a new rotate( ) method. This interface can easily be implemented by adapting the CircularlyLinkedList class to produce a new LinkedCircularQueue class. This class has an advantage over the traditional LinkedQueue, because a call to Q.rotate( ) is implemented more efficiently than the combination of calls, Q.enqueue(Q.dequeue( )), because no nodes are created, destroyed, or relinked by the implementation of a rotate operation on a circularly linked list. A circular queue is an excellent abstraction for applications in which elements are cyclically arranged, such as for multiplayer, turn-based games, or round-robin scheduling of computing processes.
  • 14. Data Structures and Algorithms in Java 14/21 Queue Interface in Java - 1 • Java interface corresponding to our Queue ADT • Requires the definition of class EmptyQueueException • No corresponding built-in Java class public interface Queue { public int size(); public boolean isEmpty(); public Object front() throws EmptyQueueException; public void enqueue(Object o); public Object dequeue() throws EmptyQueueException; }
  • 15. Data Structures and Algorithms in Java 15/21 Double-Ended Queues (Deque) - 1 15 We next consider a queue-like data structure that supports insertion and deletion at both the front and the back of the queue. Such a structure is called a doubleended queue, or deque, which is usually pronounced “deck” to avoid confusion with the dequeue method of the regular queue ADT, which is pronounced like the abbreviation “D.Q.” The deque abstract data type is more general than both the stack and the queue ADTs. The extra generality can be useful in some applications. For example, we described a restaurant using a queue to maintain a waitlist. Occasionally, the first person might be removed from the queue only to find that a table was not available; typically, the restaurant will reinsert the person at the first position in the queue. It may also be that a customer at the end of the queue may grow impatient and leave the restaurant.
  • 16. Data Structures and Algorithms in Java 16/21 Double-Ended Queues (Deque) - 2 16 The deque abstract data type is richer than both the stack and the queue ADTs. To provide a symmetrical abstraction, the deque ADT is defined to support the following update methods: addFirst(e): Insert a new element e at the front of the deque. addLast(e): Insert a new element e at the back of the deque. removeFirst( ): Remove and return the first element of the deque (or null if the deque is empty). removeLast( ): Remove and return the last element of the deque (or null if the deque is empty). Additionally, the deque ADT will include the following accessors: first( ): Returns the first element of the deque, without removing it (or null if the deque is empty). last( ): Returns the last element of the deque, without removing it (or null if the deque is empty). size( ): Returns the number of elements in the deque. isEmpty( ): Returns a boolean indicating whether the deque is empty.
  • 17. Data Structures and Algorithms in Java 17/21 Priority Queues 17 • A priority queue can be assigned to enable a particular process, or event, to be executed out of sequence without affecting overall system operation • FIFO rule is broken in these situations • In priority queues, elements are dequeued according to their priority and their current queue position
  • 18. Data Structures and Algorithms in Java 18/21 Array implementation of a priority queue - 1 18 class PriorityQueue { protected float [] a; int top, max; public PriorityQueue() { this(50); } public PriorityQueue(int max1) { max = max1; a = new float[max]; top = -1; } protected boolean grow() { int max1 = max + max/2; float [] a1 = new float[max1]; if(a1 == null) return(false); for(int i =0; i<=top; i++) a1[i] = a[i]; a = a1; return(true); } public boolean isEmpty() { return(top==-1);} public boolean isFull() { return(top==max-1);} public void clear() { top=-1;} public void enqueue(float x) { if(isFull() && !grow()) return; if(top==-1) { a[0] = x; top = 0; return; } int i = top; while(i>=0 && x<a[i]) { a[i+1] = a[i]; i--; } a[i+1] = x; top++; }
  • 19. Data Structures and Algorithms in Java 19/21 Array implementation of a priority queue - 2 19 public float front() { assert(!isEmpty()); return(a[top]); } public float dequeue() {assert(!isEmpty()); float x = a[top]; top--; return(x); }
  • 20. Data Structures and Algorithms in Java 20/21 Summary 20 • A queue is a waiting line that grows by adding elements to its end and shrinks by taking elements from its front. • A queue is an FIFO structure: first in/first out. • In queuing theory, various scenarios are analyzed and models are built that use queues for processing requests or other information in a predetermined sequence (order). • A priority queue can be assigned to enable a particular process, or event, to be executed out of sequence without affecting overall system operation. • In priority queues, elements are dequeued according to their priority and their current queue position.
  • 21. Data Structures and Algorithms in Java 21/21 Reading at home Text book: Data Structures and Algorithms in Java • 6.2 Queues - 238 • 6.3 Double-Ended Queues (Deque) - 248 • 9.1 The Priority Queue Abstract Data Type - 360

Editor's Notes

  1. Messaging application (Inter-networking)