Friday 15 April 2016

HEAP SORT C++ IMPLEMENTATION

#include<iostream>
using namespace std;

class sort
{
int a[10],n,i,j,size;
    public:
void val();
void buildmax();
void maxheapify(int);
void heapsort();
void print();
};
void sort::val()
{
cout<<"Enter element Size : ";
cin>>n;
for(i=1;i<=n;i++)
{
cout<<"elem "<<i<<" : " ;
cin>>a[i];
}
i=1,j=n;

}
void sort::heapsort()
{
int temp;
buildmax();
for(i=n;i>=2  ;i--)
{
temp=a[i];
a[i]=a[1];
a[1]=temp;
size=size-1;
maxheapify(1);
}
}


void sort::buildmax()
{
size=n;
for(i=n/2;i>=1;i--)
maxheapify(i);
}
void sort::maxheapify(int i)
{
int lar;
int l=i*2;
int r=i*2+1;
if(l<=size&&a[l]>a[i])
lar=l;
else
lar=i;
if(r<=size&&a[r]>a[lar])
lar=r;
if(i!=lar)
{
int temp=a[i];
a[i]=a[lar];
a[lar]=temp;
maxheapify(lar);
}

}

void sort::print()
{
cout<<"\n\theap Sort\n";
for(i=1;i<=n;i++)
cout<<"\t"<<a[i];
}
int main()
{
sort obj;
obj.val();
obj.heapsort();
obj.print();
}

No comments:

Post a Comment