Tuesday, January 19, 2010

PRIORITY QUEUE

#include
#include
#include
#include

void insert(int [],int);
void remove(int[]);
void print(int[]);
void heapify(int[],int);
void adjust(int[],int,int);

int n=0; //size of array initialized to 0

void main()
{
clrscr();
char c;
int a[50];
int ch=0;
// for(i=1;i<=50;i++)
// a[i]=0;
while(ch==0)
{
cout< cout< cout< cout< cout< cin>>ch;
switch(ch)
{
case 1:
{
int x;
do
{
cout< cin>>x;
insert(a,x);
cout<<"Do you want to insert again(y/n)::";
cin>>c;
}while(c=='y' || c=='Y');
if(c=='n' || c=='N')
{
ch=0;
break;
}
}
case 2:
{
do
{
remove(a);
cout< cin>>c;
}while(c=='y' || c=='Y');
if(c=='n' || c=='N')
{
ch=0;
break;
}
}
case 3:
{
print(a);
ch=0;
break;
}
case 4:
{
ch=5;
exit(0);
}
}
}
getch();
}

void insert(int a[],int x)
{
if(n==0)
{
a[1]=x;
n++;
}
else
{
a[n+1]=x;
heapify(a,n+1);
n++;
}
}

void remove(int a[])
{
if(n==0)
cout<<"The queue is empty";
else
{
int item=a[1];
cout< a[1]=a[n];
a[n]=item;
n=n-1;
heapify(a,n);
}
}

void print(int a[])
{
if(n==0)
cout< else
{
cout< for(int i=1;i<=n;i++)
cout< }
}

void heapify(int a[],int n)
{
for(int i=n/2;i>=1;i--)
adjust(a,i,n);
}

void adjust(int a[],int i,int n)
{
int j=2*i;
int item=a[i];
while(j<=n)
{
if((j j=j+1;
if(item>=a[j])
break;
a[j/2]=a[j];
j=2*j;
}
a[j/2]=item;
}

No comments: