#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class heap
{
private:
int a[20],n;
public:
void read();
void creatheap();
void sort();
void display();
};
void heap::read()
{
cout<<"Enter the limit : ";
cin>>n;
cout<<"Enter "<<n<<" elements : ";
for(int i=0;i<n;i++)
cin>>a[i];
}
void heap::display()
{
for(int i=0;i<n;i++)
cout<<" "<<a[i];
}
void heap::creatheap()
{
int par,num,loc;
for(int i=0;i<n;i++)
{
loc=i;
num=a[i];
while(loc>0)
{
par=(loc-1)/2;
if(num<=a[par])
{
a[loc]=num;
return;
}
a[loc]=a[par];
loc=par;
}
a[0]=num;
}
}
void heap::sort()
{
int last,left,right,i;
for(last=n-1;last>0;last--)
{
i=0;
int temp=a[i];
a[i]=a[last];
a[last]=temp;
left=2*i+1;
right=2*i+2;
while(right<last)
{
if(a[i]>=a[left]&&a[i]>=a[right])
return;
if(a[right]<=a[left])
{
temp=a[i];
a[i]=a[left];
a[left]=temp;
i=left;
}
else
{
temp=a[i];
a[i]=a[right];
a[right]=temp;
i=right;
}
left=2*i+1;
right=2*i+2;
}
if(left==last-1 && a[i]<a[left])
{
temp=a[i];
a[i]=a[left];
a[left]=temp;
}
}
}
void main()
{
clrscr();
heap h;
h.read();
h.creatheap();
cout<<"Heap elements are : ";
h.display();
h.sort();
cout<<endl;
cout<<"Sorted elements are : ";
h.display();
getch();
}
No comments:
Post a Comment