Saturday, November 24, 2012

C++ program for Heapsort

#include<iostream>
#define SIZE 9
using namespace std;
void Maxheapify(int A[SIZE],int i,int heapsize)
{
int largest=i;
if(2*i <heapsize && A[i]<A[2*i])
{
largest=2*i;
}
if(2*i+1 <heapsize && A[largest]<A[2*i+1])
{
largest=2*i+1;
}
if(largest!=i)
{
int t=A[i];
A[i]=A[largest];
A[largest]=t;
Maxheapify(A,largest,heapsize);
}
}
void Buildmaxheap(int A[SIZE],int heapsize)
{
int size=heapsize;
for(int i=size/2;i>=0;i--)
{
Maxheapify(A,i,heapsize);
}
}
void Heapsort(int A[SIZE])
{
Buildmaxheap(A,SIZE);
cout<<endl;
int heapsize=SIZE;
for(int i=SIZE-1;i>=1;i--)
{
int t=A[0];
A[0]=A[i];
A[i]=t;
heapsize--;
Maxheapify(A,0,heapsize);
}
}
int main()
{
int A[SIZE]={9,2,1,8,7,2,4,3,5};
cout<<"The given array:\n";
for(int i=0;i<SIZE;i++)
{
cout<<A[i]<<" ";
}
Heapsort(A);
cout<<"The sorted array:\n";
for(int i=0;i<SIZE;i++)
{
cout<<A[i]<<" ";
}
cout<<endl;
}

No comments:

Post a Comment