Heap is an array which stores elements in unsorted order. When an element is poped out it gives the minimum or maximum element (eg. 5,8,2,9,1) it will give 1,2,5,8,9.
#include<iostream>
using namespace std;
int n,g[20],ctr=0;;
void heapsort(int a[],int n);
void heapify(int a[],int n);
void delheap(int a[])
{
int i,t,p;
g[ctr++]=a[0];
a[0]=a[n];
n--;
p=(n%2==1)?(n-1)/2:(n-2)/2;
if(a[p]>a[0])
{
swap(a[p],a[0]);
delheap(a);
}
}
int main()
{
int a[20];
int i=0,j=0;
cout<<"enter the elements";
cin>>n;
while(n!=-1)
{
a[i++]=n;
cin>>n;
}
n=i;
heapsort(a,n);
cout<<"\nsorted numbers are ";
delheap(a);
for(i=0;i<n;i++)
cout<<g[i]<<" ";
return 0;
}
void swap(int &a,int &b)
{
int temp=a;
a=b;
b=temp;
}
void heapsort(int a[],int n)
{
int i,t;
for(i=n-1;i>0;i--)
{
int p;
p=(i%2==1)?(i-1)/2:(i-2)/2;
if(a[p]>a[i])
{
swap(a[p],a[i]);
heapsort(a,p);
}
}
}
#include<iostream>
using namespace std;
int n,g[20],ctr=0;;
void heapsort(int a[],int n);
void heapify(int a[],int n);
void delheap(int a[])
{
int i,t,p;
g[ctr++]=a[0];
a[0]=a[n];
n--;
p=(n%2==1)?(n-1)/2:(n-2)/2;
if(a[p]>a[0])
{
swap(a[p],a[0]);
delheap(a);
}
}
int main()
{
int a[20];
int i=0,j=0;
cout<<"enter the elements";
cin>>n;
while(n!=-1)
{
a[i++]=n;
cin>>n;
}
n=i;
heapsort(a,n);
cout<<"\nsorted numbers are ";
delheap(a);
for(i=0;i<n;i++)
cout<<g[i]<<" ";
return 0;
}
void swap(int &a,int &b)
{
int temp=a;
a=b;
b=temp;
}
void heapsort(int a[],int n)
{
int i,t;
for(i=n-1;i>0;i--)
{
int p;
p=(i%2==1)?(i-1)/2:(i-2)/2;
if(a[p]>a[i])
{
swap(a[p],a[i]);
heapsort(a,p);
}
}
}
No comments:
Post a Comment