I was implementing a heapsort algorithm in C according to CLRS. However I am unable to get a sorted output. Can you please have a look and tell what is wrong with my code. Functions maxheap
and buildmaxheap
works. I am not able to figure what is wrong with the code.
The code is supposed to heapsort the array elements. I feel there is an error in the heapsort()
function as the maxheap
and buildmaxheap
work just fine.
The final output I am getting is
1 1 1 1 2 1 2 2 1 1
But the expected output should be
1 2 3 4 7 8 9 10 14 16
The code:
#include<stdlib.h>
#include<stdio.h>
#define maxn 11
int n=10;
int parent(int i)
{
return i/2;
}
int left(int i)
{
return 2*i+0;
}
int right(int i)
{
return 2*i+1+0;
}
void max_heap(int x[],int i,int heapsize)
{
int largest;
int l=left(i);
int r=right(i);
if (l<=heapsize && x[l]>x[i]){
largest=l;
}
else
{
largest=i;
}
if (r<=heapsize && x[r]>x[largest]){
largest=r;
}
if (largest!=i)
{
int s=x[i];x[i]=x[largest];x[largest]=s;
max_heap(x,largest,heapsize);
}
}
void buildmaxheap(int x[],int heapsize)
{
int i;
for(i=5;i>=1;i--)
max_heap(x,i,heapsize);
}
void heapsort(int x[])
{
buildmaxheap(x,10);
int i,t,heapsize=10;
for(i=10;i>=2;i--)
{
int s=x[i];x[1]=x[i];x[i]=s;
heapsize--;
/*
printf("%d",heapsize);
*/
max_heap(x,i,heapsize);
}
for(i=1;i<=10;i++)
printf("%d\t",x[i]);
}
int main()
{
int x[maxn],i;
x[1]=16;
x[2]=4;
x[3]=10;
x[4]=14;
x[5]=7;
x[6]=9;
x[7]=3;
x[8]=2;
x[9]=8;
x[10]=1;
heapsort(x);
/*
for(i=1;i<=10;i++)
printf("%d\t",x[i]);
*/
}