Friday 26 October 2012

HEAP SORT


#include<iostream.h>
#include<conio.h>
class heap
{
int a[20],n;
public:void read();
void create();
void heapsort();
void adjust(int);
};
void heap::read()
{
cout<<"enter elements\n";
for( int i=0;i<n;i++)
{
cin>>a[i];
}
}
void heap::heapsort()
{
int i,temp;
heapcreate(
);
for(i=n-1;i>0;i--)
{
temp=a[0];
a[0]=a[i];
a[i]=temp;
adjust(i);
}
}
void heap::create()
{
int i,j,k,item;
for(k=1;k<=n;k++)
{
item=a[k];
i=k;
j=(i-1)/2;
while(i>0 && item>a[j])
{
a[i]=a[j];
i=j;
j=(i-1)/2;
}
a[i]=item;
}
void heap::adjust(int x)
{
int i,j,k,item;
j=0;
item=a[j];
i=2*j+1;
while(i<=x-1)
{
if(i+1<=x-1)
if(a[j]<a[i+1])
i++;
if(item<a[i];
{
a[i]=a[j];
j=i;
i=2*j+1;
}
else
break;
}
a[j]=item;
}
void heap::show()
{
cout<<"sorted array is \n";
for(int i=0;i<n;i++)
{
cout<<a[i]<<"\n";
int main()
{
heap h;
int temp,i,m;
clrscr();
cout<<"enter no of elements\n";
cin>>m;
h.getdata(m);
cout<<"before sort\n";
h.show();
h.heapsort();
cout<<"after sort\n";
h.show();
getch();
return(0);
}
}

No comments:

Post a Comment