C++ program to implement Heap sort algorithm using heap contruction.
C++ program to implement heap sort
#include<iostream>
using namespace std;
class sort_list
{
int a[20];
int n1,n,m;
public:
void get_data();
void buildheap();
void maxheapify(int);
void heapsort();
void display();
};
void sort_list::get_data()
{
cout<<"How many elements two be entered ";
cin>>n;
cout<<"Enter the elements ";
for(int i=0;i<n;i++)
cin>>a[i];
m=n;
}
void sort_list::maxheapify(int i){
int l,r,max,temp;
l=2*i+1;
r=2*i+2;
if(l<m&&a[l]>a[i])
max=l;
else max=i;
if(r<m&&a[r]>a[max])
max=r;
if(max!=i){
temp=a[i];
a[i]=a[max];
a[max]=temp;
maxheapify(max);
}
}
void sort_list::buildheap(){
int i;
for (i = m/2; i>=0 ; --i)
maxheapify(i);
}
void sort_list::heapsort(){
buildheap();
int temp;
m--;
while(m){
temp=a[m];
a[m]=a[0];
a[0]=temp;
maxheapify(0);
m--;
}
}
void sort_list::display()
{
cout<<"Sorted list : ";
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
}
int main()
{
sort_list sort;
sort.get_data();
sort.heapsort();
sort.display();
return 0;
}
using namespace std;
class sort_list
{
int a[20];
int n1,n,m;
public:
void get_data();
void buildheap();
void maxheapify(int);
void heapsort();
void display();
};
void sort_list::get_data()
{
cout<<"How many elements two be entered ";
cin>>n;
cout<<"Enter the elements ";
for(int i=0;i<n;i++)
cin>>a[i];
m=n;
}
void sort_list::maxheapify(int i){
int l,r,max,temp;
l=2*i+1;
r=2*i+2;
if(l<m&&a[l]>a[i])
max=l;
else max=i;
if(r<m&&a[r]>a[max])
max=r;
if(max!=i){
temp=a[i];
a[i]=a[max];
a[max]=temp;
maxheapify(max);
}
}
void sort_list::buildheap(){
int i;
for (i = m/2; i>=0 ; --i)
maxheapify(i);
}
void sort_list::heapsort(){
buildheap();
int temp;
m--;
while(m){
temp=a[m];
a[m]=a[0];
a[0]=temp;
maxheapify(0);
m--;
}
}
void sort_list::display()
{
cout<<"Sorted list : ";
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
}
int main()
{
sort_list sort;
sort.get_data();
sort.heapsort();
sort.display();
return 0;
}
No comments:
Post a Comment