Friday, October 2, 2009

ADA 5th sem lab prgms

/* Program No: 02.
Sort a given set of elements using the Heap Sort method..*/
/* C program to sort a given list of numbers using Heap Sort*/
#include
#include
int num[50], elements=0, old, new;
int highest(int num[])
{
int m, max=0, index;
for(m=1;m<=elements+1;m++)
if(max max=num[m],index=m;
num[index]=0;
return max;
}
int compare(int a, int b)
{
if(num[a]==0&&num[b]==0)
return -1;
if(num[a]>num[b])
return 0;
else
return -1;
}
void exchange(int a, int b)
{
int temp;
temp=num[a];
num[a]=num[b];
num[b]=temp;
}
void insert(int new)
{
int k;
elements++;
num[elements]=new;
k=elements;
while(k>1)
{
old=k/2;
if(compare(k,old)>=0)
break;
exchange(k,old);
k=old;
}
}
void rem()
{
int k=1,new;
printf("%d\n",num[1]);
num[1]=highest(num);
while((2*k)<=elements)
{
if(num[2*k]==0||num[2*k+1]==0)
{
if(num[2*k]==0)
new=2*k+1;
else
new=2*k;
}
else
if(compare(2*k,2*k+1)<0)
new=2*k;
else
new=2*k+1;
if(compare(k,new)<0)
break;
exchange(k,new);
k=new;
}
}
void main()
{
int a,i,n,par=0;
clrscr();
printf("input the number of elements\n");
scanf("%d",&n);
printf("input the %d elements\n",n);
for(i=0;i {
scanf("%d",&a);
insert(a);
}
printf("sorted order is\n");
for(i=0;i rem();
par=highest(num);
printf("%d\n",par);
getche();
}

/* Output:
input the number of elements
5
inter the 5 elements
64
24
46
84
28
sorted order is
24
28
46
64
84
..........*/

No comments:

Post a Comment