CH 3 - Queue
CH 3 - Queue
Queue
Queue
Definition
return 0;
}
Static Implementation [4]
return 0;
}
Static Implementation [5]
Algorithm Enqueue(q,x):
1. Start
2. Check if queue is full, if not go to step 3,
Else go to step 5:
3. Increment rear: rear++;
4. Insert x into q->items[rear]
5. Stop
Static Implementation [5]
Algorithm Dequeue(q):
1. Start
2. Check if queue is empty, if not go to step 3,
Else go to step 5:
3. Read from q->items[front]
4. Increment front.
5. Stop
Problems with linear queue
● 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.
Dynamic Implementation[1]
Circular Queue
● A queue where the start and end of the queue are joined together.
● A circular queue overcomes the problem of unutilized space in linear queue
implementation as array.
● 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.
● It is also called Ring Buffer.
● In circular queue we sacrifice one element of the array. Thus to insert n
elements in a circular queue we need an array of size n+1.(or we can insert
one less than the size of the array in circular queue).
Dynamic Implementation[2]
● Declaration of a Circular Queue:
# define MAXSIZE 50 /* size of the circular queue items*/
Struct cqueue{
int front;
int rear;
int items[MAXSIZE];
};
typedef struct cqueue cq;
● Initialization of Circular queue:
rear=front=MAXSIZE-1
Dynamic Implementation[3]
● This algorithm assumes that rear and front are initially set to MAZSIZE-1.
Dynamic Implementation[5]
Dynamic Implementation[6]
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 and
processed comes from 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.
● The best application of priority queue is observed in CPU scheduling.
○ 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 short job is given higher priority over the longer one.
Priority Queue Types
● Set the front as the position of the smallest element and the rear as the
position of the largest element.
● To insert an element, locate the proper position of the new element and shift
preceding or succeeding elements by one position.
● To delete the minimum element, increment the front position.
Array implementation of priority queue: