Monday, June 25, 2018

Priority Queue - DS (C Program)

#include<stdio.h>
void display(int q[],int *front,int *rear)
{
int i;
if(*front == -1)
{
printf("\nQueue Underflow...");
return;
}
else
{       printf("\n");
for(i=*front;i<=*rear;i++)
{
printf("| %d ",q[i]);
}
printf("|");
}
}
void sort(int q[],int *front,int *rear)
{
int i,j;
int temp;
for(i=*front;i<=*rear;i++)
{
for(j=i+1;j<=*rear;j++)
{
if(q[j]>q[i])
{
temp=q[i];
q[i]=q[j];
q[j]=temp;
}
}
}
}
void qinsert(int q[],int *front,int *rear,int n,int size)
{
if(*rear >= size-1)
{
printf("\nQueue Overflow...");
return;
}
else
{
(*rear)++;
q[*rear]=n;
if(*front == -1)
*front=0;
sort(q,front,rear);
printf("\n");
display(q,front,rear);

/*for(i=*front;i<=*rear;i++)
{
printf("| %d ",q[i]);
}
printf("|");*/
}

}
int qdelete(int q[],int *front,int *rear)
{
int x;
if(*front == -1)
{
printf("\nQueue Underflow...");
return 0;
}
else
{
      x=q[*front];
      if(*front == *rear)
*front=*rear=-1;
      else
(*front)++;
      return x;
}
}
void main()
{
int q[5],front=-1,rear=-1,n,opt;
int size=5;
clrscr();
again:
printf("\n\n1. Insertion\n2. Deletion\n3. Display\n4. Exit");
printf("\n >> ");
scanf("%d",&opt);
switch(opt)
{
case 1: printf("\nEnter element : ");
scanf("%d",&n);
qinsert(q,&front,&rear,n,size);
goto again;
break;
case 2: n=qdelete(q,&front,&rear);
if(n!=0)
printf("\nDeleted Element : %d",n);
goto again;
break;
case 3: display(q,&front,&rear);
goto again;
break;
case 4: goto exit;
break;
default: printf("\nInvalid option...");
goto again;
break;
}
exit:
}

No comments:

Post a Comment