Tuesday, October 14, 2008

6.10.C HEAP SORT

#include
#include
#include
#include
int a[20];
class heap
{
public:
void cheap(int *a,int n);
};
void heap::cheap(int a[],int n)
{
int i,parent,child,next;
for(i=2;i<=n;i++)
{
next=a[i];
child=i;
parent=child/2;
while(child>1&&next>a[parent])
{
a[child]=a[parent];
child=parent;
parent=child/2;
if(parent<1)
parent=1;
}
a[child]=next;
}
}
void main()
{
heap h;
int n,i,last,temp;
clrscr();
cout<<"enter n value:";
cin>>n;
cout<<"enter array elements"<for(i=1;i<=n;i++)
cin>>a[i];
h.cheap(a,n);
for(last=n;last>=2;last--)
{temp=a[1];
a[1]=a[last];
a[last]=temp;
h.cheap(a,last-1);
}
cout<<"enter stored elements"<for(i=1;i<=n;i++)
cout<<" "<getch();
}
Heap sort sample input and out put
enter n value:5
enter array elements
2
1
4
3
0
enter stored elements
0 1 2 3 4

No comments: