Question

this is my program which works with three functions to perform heapsort. i m not able to figure out where is the problem in it. ll be glad if someone ll help.

this two functions calculate left and right of an index

int left(int i)
{return(2*i+1);}

int right(int i)
{return(2*i+2);}

max here is maximum array index. a is the array i is the index

void maxheapify(int i,int *a,int max)
{
 if(i>(max-1)/2)
 return;
 else
 {
     int big=0,temp=0;

     if(a[i]<a[left(i)])
     big=left(i);

     if(right(i)<=max && a[i]<a[right(i)])
     big=right(i);

     if(big==i)
     return;

     else
     {
         temp=a[big];
         a[big]=a[i];
         a[i]=temp;
         maxheapify(big,a,max);
     }
 }
 }

void buildmaxheap(int *a,int max)
{
 int i;

 for(i=0;i<=(max-1)/2;i++)
 maxheapify(i,a,max);

}     

void heapsort(int *a,int max)
{
     int j=0,temp=0;

 for(j=max;j>0;j--)
 {
                   buildmaxheap(a,j);
                   temp=a[0];
                   a[0]=a[j];
                   a[j]=temp;
 }
 }
Était-ce utile?

La solution

There is one thing I am noticing about your code. Your left and right conditions can both be satisfied one right after another. Resulting in the right moving to the parent, but there is no guarantee that right(i) >= left(i). I feel like this might cause some ordering problems after the heap has finished

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top