Sunday 9 November 2014

Heap Sort

 max(int a[],int as,int b)
{
    if(a[as]>a[b])return as;
        else return b;
}

pqins(int a[],int lb,int ub)
{
int i=1,j,k;l
while(i!=0)
{
i=0;
int j,k;
for(j=ub;j>=lb;j--)
{
k=j/2;
if(a[k]<a[j]&&k>=lb)//Parent node should be greater than child node
    {
        a[k]=a[k]+a[j];
        a[j]=a[k]-a[j];
        a[k]=a[k]-a[j];
        i++;
    }
}
}
}
heapify(int a[],int lb,int ub)
{
    int k=0;
    while((2*k)+1<=ub)
    {
int l;
l=max(a,(2*k)+1,(2*k)+2);
if(2*(k+1)>ub){l=(2*k)+1;}
    a[k]=a[l];
    k=l;
    }
    a[k]=-1;
}

main()
{
int ka;
printf("Enter the total number of numbers to be sorted\n");
scanf("%d",&ka);
int a[ka];
int l;
for(l=0;l<ka;l++)
{
    printf("Enter element %d\n",l+1);
    scanf("%d",&a[l]);
}
pqins(a,0,ka-1);//Function to make heap
int result[ka];
int k;
for(k=0;k<ka;k++)
{
    result[k]=a[0];
    heapify(a,0,ka-1);//Function to remake heap after taking the maximum element
}
printf("\nSORTED ARRAY IS \n");
int i;
for(i=0;i<ka;i++)printf("%d\n",result[i]);
}

No comments:

Post a Comment