Beruflich Dokumente
Kultur Dokumente
Queue Overview
Queue ADT
Basic operations of queue
Circular queue
Priority queue
Queue
What is a queue?
rear B
front A
C
rear B
fron A
t
D
rear C
B
front A
rear
D
C
front B
rear
front
Queue ADT
abstract typedef<<eltyper> QUEUE (eltype);
abstract empty(q)
QUEUE(eltype) q;
postcondition empty== len(q)==0;
abstract eltype remove(q)
QUEUE (eltype) q;
precondition: empty(q) == FALSE
postcondition remove == first(q`);
q== sub(q`,1, len(q`) -1;
Queue ADT
Abstract insert(q, elt);
QUEUE (eltype) q;
eltype elt;
postcondition q == q + <elt> ;
Implementation of Queues
Array Implementation
Queue
void
insert(queue *q, int
Operations
x)
{
if ( q->rear==SIZE-1)
{
cout <<Queue overflow;
exit(1) ;
}
else
q->items[++q->rear)]=x;
}
Call of function will be like insert(&q, 2);
Queue
intOperations
remove(queue *q)
{
if (empty())
{
cout <<Queue underflow;
exit(1);
}
return(q->items[q->front++]);
}
Queue Array
Solution 1
When ever remove is called move all the elements in the
start of queue.
x = q.items[0]
for (int i=0; i <q.rear; i++)
q.items[i] = q.items[i+1];
q.rear--;
Solution 2
These problems can be avoided by
using a circular array an array in
which the location of the front and
back index are allowed to change
and the contents to wrap around
when the last position in the buffer
is filled.
Circular Queue
Imagine that the two ends are joined together to form a
circle implemented by a circular
Queue
array
The Queue maintains two indices, front and rear, that initially are
both SIZE -1
1
0
3
rear
front
4
8
7
5
6
Insertion in queue
1
rear
back
4
0
front
x
5
9
8
6
7
x
1
back
front
front
4
rear
5
9
8
6
7
buffer
x
1
back
front
rear
5
9
8
6
7
buffer
Circular Array
Implementation
Queue
Operations
Queue
Operations
2
front
rear
X
9
X
8
X
7
X
6
Queue
Operations
2
front
rear
X
9
X
8
X
7
Queue
Operations
Priority Queues
isEmpty
insert an element into the priority queue
get element with min priority
remove element with min priority
isEmpty
insert an element into the priority queue
get element with max priority
remove element with max priority
Applications
Sorting
use element key as priority
put elements to be sorted into a
priority queue
extract elements in priority order
Sorting Example
Sort five elements whose keys are 6, 8,
2, 4, 1 using a max priority queue.
4
1
Sorted Array
Max
Priority
Queue
Max
Priority
Queue
Sorted Array
Max
Priority
Queue
Sorted Array
Max
Priority
Queue
Sorted Array
Sorted Array
Sorted Array
Queue
Operations
Deletion Operation
Solutions
1.A special empty() indicator can be placed
into a deleted position. Insertion is done
as given before.
2.Deletion operation labels a position as
empty but insertion is done at the first
empty position.
3.Each deletion compact the array by
shifting all elements past the deleted
element by one position and
decrementing pq.rear by 1.
4.Keep the array sorted.