Saturday, February 20, 2010

Sort the given set of elements using heap sort

WHEREVER U SEE ... REMOVE THAT . AND PUT << IN THAT PLACE.
IF YOU SEE .. THEN REMOVE THAT . AND PUT < IN THAT PLACE..
3.#include..iostream.h>
#include..stdlib.h>

//function to create the heap
void heapcreate(int a[],int n)
{
int i,j,k,item;
for(k=2;k..=n;k++)
{
item =a[k];
i=k;
j=i/2;
while(j!=0 && item > a[j])
{
a[i]=a[j];
i=j;
j=i/2;
}
a[i]=item;
}
}


//function to recreate the heap
void adjust(int a[],int n)
{
int i,j,item;
j=1;
item=a[j];
i=2*j;
while(i..=n-1)
{
if(i+1..=n-1)
if(a[i]..a[i+1])
i++;
if(item..a[i])
{
a[j]=a[i];
j=1;
i=2*j;
}

else
break;
}
a[j]=item;
}

//function for heap sort
void heapsort(int a[],int n)
{
int i,temp;
heapcreate(a,n);
for(i=n;i>=1;i--)
{
temp=a[1];
a[1]=a[i];
a[i]=temp;
adjust(a,i);
}
}

//main function
void main(){
int a[20],n,temp;
cout..."Enter the number of elements\n";
cin>>n;
cout..."Enter the elements to be sorted\n";
for(int i=1;i..=n;i++)
cin>>a[i];
heapsort(a,n);
cout..."The sorted elements are ";
for(i=1;i..=n;i++)
cout...a[i]...endl;
}













Output

Enter the no of elements
5
Enter the elements to be sorted
23
12
5
16
4

Sorted elements are:
4
5
12
16
23

No comments:

Post a Comment