Friday, 27 April 2012

Program for Heap Sort in C

The time complexity of Heap Sort algorithm is, 


Best Case - O(n log n)
Average Case - O(n log n)
Worst Case - O(n log n)


Here's the code for Heap Sort in C,

#include<stdio.h>
#include<conio.h>

int main()
{
    int a[50];
    int n;
    clrscr();
    printf("\nEnter n: ");
    scanf("%d",&n);
    enter(a,n);
    printf("\nBefore sort : \n");
    display(a,n);
    heapsort(a,n);
    printf("\nAfter sort : \n");
    display(a,n);
getch();
return 0;
}

int enter(int a[],int x)
{
    int i;
    printf("\nEnter %d values \n",x);
    for(i=1;i<=x;i++)
    {
	scanf("%d",&a[i]);
    }
    return;
}

int display(int a[],int x)
{
    int i;
    for(i=1;i<=x;i++)
    {
	printf("%d ",a[i]);
    }
    return;
}

int heapsort(int a[],int n)
{
    int i,j,z;
    for(i=n/2;i>=1;i--)
    {
	steps(a,i,n);
    }
    for(i=n-1;i>=1;i--)
    {
	printf("\n");
	display(a,n);
	z=a[i+1];
	a[i+1]=a[1];
	a[1]=z;
	steps(a,1,i);
    }
    return;
}
int steps(int a[],int pos,int x)
{
    int data,j;
    data=a[pos];
    j=pos*2;
    while(j<=x)
    {
	if(j<x)
	{
	if(a[j]<a[j+1])
	{
	    j=j+1;
	}
     }
    if(a[j]>data)
    {
	a[j/2]=a[j];
	j=j*2;
    }
	else
		break;
	}
	a[j/2]=data;
	return;
}

No comments:

Post a Comment