nando hidayat
nando hidayat

Reputation: 21

Passing pointer from recursive function

I've been ask to make selection sort code with only recursive method. So i think about making another function to find array that store max value then switch it in my other function.

void p_rec_max(int data[], int cur, int arrSize,int * x) {
    if(cur < arrSize - 1) {
        if(data[cur] > data[arrSize - 1]) {
            *x = cur;
        } else if(data[cur] < data[arrSize - 1]){
            *x = arrSize - 1;
        }
        p_rec_max(data,cur + 1,arrSize,&x);
    }
}

void rec_selection_sort(int data[], int arrSize) {
    if(arrSize > 0) {
        int maxi,temp;
        p_rec_max(data,0,arrSize,&maxi);
        temp = data[arrSize - 1];
        data[arrSize - 1] = data[maxi];
        data[maxi] = temp;
        rec_selection_sort(data,arrSize - 1);
    }
}

It got some warning like this

In function 'p_rec_max': warning: passing argument 4 of 'p_rec_max' from incompatible pointer type [enabled by default] note: expected 'int *' but argument is of type 'int **'

And it does not change my array at all. My lack of information of passing pointer in function can't help me to fix that problem. Could you guys fix my code and then explain to me of what is wrong about my code? Thanks

Upvotes: 0

Views: 528

Answers (1)

4386427
4386427

Reputation: 44274

First problem

You have a problem with this line:

p_rec_max(data,cur + 1,arrSize,&x);
                               ^^

Since x is a int *, &x is a int ** which isn't what the function expects.

Change the line to:

p_rec_max(data,cur + 1,arrSize, x);

i.e. no & in front of x

Second problem

Your p_rec_max function doesn't find the index of the maximum array value.

If all array elements are the same, the code will never execute a *x = .... In other words maxi will never be written and you end up using an uninitialized index here data[arrSize - 1] = data[maxi]; That is undefined behavior and may crash your program.

Besides that I think the basic logic in the function is wrong. The code always compare cur to the last array element. That seems wrong. I think you should compare cur to the value of the maximum found so far. That could be done using the variable x.

Something like:

void p_rec_max(int data[], int cur, int arrSize,int * x) {
    if(cur < arrSize) {
        if(data[cur] > data[*x]) {
            *x = cur;
        }
        p_rec_max(data, cur + 1, arrSize, x);
    }
}

and in rec_selection_sort call it like:

    maxi = 0;  // Assume index zero holds the maximum
    p_rec_max(data, 1, arrSize, &maxi);
                    ^
                 Start searching from index 1

BTW: Using a recursive function to find the maximum value in an array is of cause not a good approach but I guess you are not allowed to use a simple foror while loop.

Upvotes: 2

Related Questions