Highest value of a vector, with recursion

2

I'm studying about recursion and vectors, but I can not figure out how this method works, which returns the highest value using recursion.

int maximoR (int n, int v[]) {
   int x;
   if (n == 1) x = v[0];
   else {
      x = maximoR (n-1, v); 
      if (x < v[n-1]) x = v[n-1];
   }
   return x;
}
    
asked by anonymous 05.09.2016 / 16:55

1 answer

3

First, this function would be called something like this:

int valores[] = {5, 10, 4, -4, 2, -7, 9};
int max = maximoR(7, valores); /* 7 = tamanho do vetor. */

Recursively, except when n is 1, it will always fall into else , creating a recursive call sequence like this (this is the process of going ):

maximoR(6, v);
maximoR(5, v);
maximoR(4, v);
maximoR(3, v);
maximoR(2, v);
maximoR(1, v);

At this point, the if will no longer drop to else and will return the v[0] element. Then, with each iteration it will start the process of back , where it will take the value of the previous iteration and it will compare with that of the n -th position of the array, always choosing the largest and returning this greater for the top call.

With this, here's what happens:

  • In the deepest iteration (the last one) it only returns the first value.
  • In the second, deepest iteration (the penultimate), it compares the second value with that obtained from the last iteration.
  • In the third, deepest iteration (the antepenultimate), it compares the third value with that obtained from the penultimate iteration.
  • ...
  • In the first iteration (the shallowest), it compares the last value with that obtained from the second iteration.

So in the end the value chosen will be the largest element.

    
05.09.2016 / 17:08