18 April 2013

programing - priority queue

if i have to clean the house,play the video games and do my homework ,what would i select to do first?
according to the degree of entertainment ,i would like to play video game first,then i will do my home work and then finally i will clean the house as it is the least entertaining job . As you can see i have given priority to my tasks so that i can do task with maximum priority (according to my criteria) first and then move to other jobs.
computers exactly uses this concept to decide which job among multiple jobs they have to process first or last.
A data structure called priority queue is used to implement this concept.In turn priority queue are implemented with the help of another data structure called heaps(more precisely min heaps or max heaps).
can you be more detailed?
sure why not .i love to be more specific
since priority queues are based on heaps we have two kinds of priority queues
minimum number of operations supported are
1.maximum (S) : returns the element of S with largest key
2.Insert (S,x) : insert element into set S.equivalent to S=S U{x}
3.extract max(S) : returns and removes element of S with largest key
4.Increase-Key (S,x,k) : increase the value of element x's key to the new value k note : k>= x 's key
int maximum(int A[]){
return A[1];
independent of input size so
time complexity : O(1) or constant
int extract_maximum(int A[],int *size){
if (*size<1) return ;
int max=A[1];
return max;
time complexity:
Worst case : O(log n);
best case :omega(1)
max_heapify will travel only 1 level down.

void increase_key(int A[],int i,int key){
if (key < A[i]) return ;
while (key > A[i/2] && i>1){
Time complexity:
worst case : O(log n)
best case : O(1) when i =1

void insert(int A[],int key int &size){
Time complexity :
worst case : In worst case the increase_key procedure will have to traverse from the child node up to the root thus covering the height of logn. so O(log n)
best case :Best case will occur when the key of the inserted element is less then that of its immediate parent.In this case the increase_key procedure will take only constant time.

so total complexity : omega(1)