#include<iostream>
using namespace std;
int k[20],heapsize;
void adjust(int i)
{
int left=2*i;
int right=2*i+1;
int largest,temp;
if(left<=heapsize && k[left]>k[i])
largest=left;
else
largest=i;
if(right<=heapsize && k[largest]<k[right])
largest=right;
if(largest!=i)
{
temp=k[i];
k[i]=k[largest];
k[largest]=temp;
adjust(largest);
}
}
void heapify(int n)
{
heapsize=n;
int i=n/2;
while(i>=1)
{
adjust(i);
i--;
}
}
void heapsort(int n)
{
int q=n;
heapify(n);
while(q>=2)
{
int temp=k[1];
k[1]=k[q];
k[q]=temp;
heapsize--;
adjust(1);
q--;
}
}
int main()
{
int n;
cout<<"\nEnter no of elements:";cin>>n;
cout<<"\nEnter elements:";
for(int i=1;i<=n;i++)
cin>>k[i];
heapsort(n);
for(int i=1;i<=n;i++)
cout<<k[i];
return 0;
}
OUTPUT:
Enter no of elements:6
Enter elements:4 1 5 3 2 6
123456
using namespace std;
int k[20],heapsize;
void adjust(int i)
{
int left=2*i;
int right=2*i+1;
int largest,temp;
if(left<=heapsize && k[left]>k[i])
largest=left;
else
largest=i;
if(right<=heapsize && k[largest]<k[right])
largest=right;
if(largest!=i)
{
temp=k[i];
k[i]=k[largest];
k[largest]=temp;
adjust(largest);
}
}
void heapify(int n)
{
heapsize=n;
int i=n/2;
while(i>=1)
{
adjust(i);
i--;
}
}
void heapsort(int n)
{
int q=n;
heapify(n);
while(q>=2)
{
int temp=k[1];
k[1]=k[q];
k[q]=temp;
heapsize--;
adjust(1);
q--;
}
}
int main()
{
int n;
cout<<"\nEnter no of elements:";cin>>n;
cout<<"\nEnter elements:";
for(int i=1;i<=n;i++)
cin>>k[i];
heapsort(n);
for(int i=1;i<=n;i++)
cout<<k[i];
return 0;
}
OUTPUT:
Enter no of elements:6
Enter elements:4 1 5 3 2 6
123456
No comments:
Post a Comment