Tuesday, January 19, 2010

HEAPSORT

#include
#include
#include

void heapsort(int [],int);
void heapify(int [],int);
void adjust(int[],int,int);

void main()
{
clrscr();
int a[50],x,i;
cout<<"Enter the size of the array::";
cin>>x;
cout< for(i=1;i<=x;i++)
cin>>a[i];
heapsort(a,x);
cout< for(i=1;i<=x;i++)
cout< getch();
}

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

void heapify(int a[],int n)
{
for(int i=floor(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: