Monday 8 February 2016

Priority Queue:
Priority Queue is more specialized data structure than Queue. Like ordinary queue, priority queue has same method but with a major difference. In Priority queue items are ordered by key value so that item with the lowest value of key is at front and item with the highest value of key is at rear or vice versa. So we're assigned priority to item based on its key value. Lower the value, higher the priority. Following are the principal methods of a Priority Queue.
Basic Operations:
insert / enqueue − add an item to the rear of the queue.
remove / dequeue − remove an item from the front of the queue.
Priority Queue Representation








We're going to implement Queue using array in this article. There is few more operations
supported by queue which are following.
Peek − get the element at front of the queue.
isFull − check if queue is full.
isEmpty − check if queue is empty.
Insert / Enqueue Operation
Whenever an element is inserted into queue, priority queue inserts the item according to its order.
Here we're assuming that data with high value has low priority.







void insert(int data)
{
int i = 0;
if(!isFull())
{
// if queue is em pty, insert the data
if(item Count == 0){
intArray[item Count++] = data;
}
Else
{
// start from the right end of the queue
for(i = item Count - 1; i >= 0; i-- )
{
// if data is larger, shift existing item to right end
if(data > intArray[i])
{
intArray[i+1] = intArray[i];
}else
{
break;
}
}
// insert the data
intArray[i+1] = data;
item Count++;
}
}
}
Remove / Dequeue Operation
Whenever an element is to be removed from queue, queue get the element using item count. Once element is removed. Item count is reduced by one.


int rem oveData()
{
return intArray[--item Count];

}

No comments:

Post a Comment