Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

#include <stdio.h>

void Heapify(int num[], int start, int end)
{
    int root = start;
    while(root*2+1<=end)
    { // at least one child exists
        int swap = root;
        int lchild = root*2+1;
        int rchild = root*2+2;
        if(num[swap]<num[lchild]){
            swap = lchild;
        }
        if(rchild<=end && num[swap]<num[rchild]){
            swap = rchild;
        }
        if(swap!=root){
                // swap here
            int temp = num[root];
            num[root] = num[swap];
            num[swap] = temp;
            root = swap;
        }
        else
            return;
    }
}

void buildHeap(int num[]) {
    int length=sizeof(num)/sizeof(num[0]);
    int start = (length/2)-1; // Starting from last parent
    int end = length-1;
    while(start>=0){
        Heapify(num,start, end);
        if(start==0)
            break;
        start= start-1;            
    }
}

void heapsort(int num[]) {
       int length=sizeof(num)/sizeof(num[0]);
        printf("length = %d ", length);   // length = 1 (Wrong)
    buildHeap(num);
    int i;  
    //for (i = 0; i < length; i++)
        //printf("%d ",num[i]);
    int end = length-1;
    while(end>0){
            // swap first elem with last
        int temp = num[0];
        num[0] = num[end];
        num[end] = temp;
        Heapify(num,0,end-1);
        end--;
    }   
}

int main() {
    int num[]={1,7,-32,4,101,-99,16,3};
    heapsort(num);

    return 0;
}

http://codepad.org/zcfNOtye

When I print it in main, the length is showing correct but inside the function(heap sort), its showing wrong. I can't find any mistakes in passing the array. What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
162 views
Welcome To Ask or Share your Answers For Others

1 Answer

Arrays decay to pointers when passed as parameters, you need to pass the length of the array as a separate parameter.

I.e.: you can't find the length of the array like this.

void buildHeap(int num[]) {
   int length=sizeof(num)/sizeof(num[0]);
} 

sizeof(num) will return sizeof(int*).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...