c - Heap Sort : how to correct my coding and to implement my logic? -


for array input 2 5 8 3 4 6 getting 2 4 5 3 8 6 trying implement heap sort , beginner , don't know error comes here , trying implement logic of heap sort building heap , interchanging last element the largest first index element , thereby decreasing size of array.

  #include<stdio.h>   #include<conio.h> 

to build highest element in starting index

  heapify(int *a,int i,int no)   {        int largest = i;       int left = 2*i;       int right = 2*i+1;       if(left<=no && a[left]>largest)       {         largest=left;       }        if(right<=no && a[right]>largest)       {           largest=right;       }        if(largest!=i)       {           int temp=a[largest];                 a[largest]=a[i];           a[i]=temp;           heapify(a,largest,no);       }   } 

to heap sort elements in array ,

  heapsort(int *a,int no)   {       while(no>1)       {           int temp=a[1];           a[1]=a[no];           a[no]=temp;           --no;           heapify(a,1,no);       }   } 

to print lements in array

  printarr(int *a,int no)   {       int i=1;        for(;i<=no;i++)           printf("%d",a[i]);         } 

this main function.

  int main()   {       int i,j,k,no,size;        printf("enter no of elements");       scanf("%d",&no);       int a[no+1];       size=no;        for(i=1;i<=no;i++)       {         scanf("%d",&a[i]);       }        printarr(a,no);       j=no/2;        for(i=j;i>0;--i)       {         heapify(a,i,no);       }        heapsort(a,no);       printarr(a,no);        getch();        return 0;   } 

you comparing index array value in heapify function

 if(left<=no && a[left]>largest) 

and

if(right<=no && a[right]>largest) 

this shuold be

 if(left<=no && a[left]>a[largest]) 

and

if(right<=no && a[right]>a[largest]) 

Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -