1

so I'm having trouble trying to understand how recursion of this code works.

int minimum(int array[], int size) {
    if (size == 1) {
        return array[0];
    }
    else {
        return (array[size] < int min = minimum(array, size - 1))? array[size] : min;
    }
}

int array[4] = {5, 99, 205, 1};
int smallest = minimum(array, 3); // 3 = index of the last element 

Here is the explanation I saw: this function searches the lowest value in an int array by using recursion. At first it checks how many elements are in the array by checking if the size equals to 1 and then returns the first value as result. If the table is bigger than 1 (and technically also when lower) it compares the last value in the array with the recursive call with the rest of the array.

The recursion stops at the 0-index and then compares that value with the index 1. Then it compares the lowest value of index 0 and 1 with the value from index 3 and so on until it reaches last value.

But I still can't imagine how the recursion run in my head, especially min = minimum(array, size - 1) . Can someone be so kind to explain it to my slow brain how this code run in stack? Thank you so much.

4
  • That code is wrong – if (size == 1) should be if (size == 0). Commented Oct 28, 2020 at 14:20
  • @Chronial - No, size==1 is right Commented Oct 28, 2020 at 14:22
  • array[size] < int min seams to be wrong syntax. Commented Oct 28, 2020 at 14:22
  • @Chronial in this case size is index of last element though, so it is correct. Commented Oct 28, 2020 at 14:23

1 Answer 1

1

I fixed the code (by accessing array[size-1] instead of array[size] and simplified it a bit (by using std::min).

int minimum(int array[], int size) {
    if (size == 1) {
        return array[0];
    } else {
        return std::min(array[size - 1], minimum(array, size - 1))
    }
}

int array[4] = {5, 99, 205, 1};
int smallest = minimum(array, 4);

Now you might be able to see that minimum(array, 4) is equal to std::min(array[3], minimum(array, 3)), is equal to std::min(array[3], std::min(array[2], minimum(array, 2))) ... is equal to std::min(array[3], std::min(array[2], std::min(array[1], array[0]))).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.