Gis B
Gis B

Reputation: 13

Finding the maximum value in a vector using recursion C++

I am trying to find the maximum value in a vector using recursion but I keep on getting a segmentation fault. I can't figure out the issue. Does anyone know why?

int find_max(vector<int> integer_array, int i) { //variable i just keeps track of the index starting at 0
    
   if(i == integer_array.size()-1) {
       return integer_array[i];
   }
    
    return max(integer_array[i], find_max(integer_array, i++));

}

//Example of a call: find_max(vector_array, 0); 

UPDATE: I know it's inefficient but this is just for practicing recursion...

Upvotes: 1

Views: 521

Answers (1)

Chen
Chen

Reputation: 330

I am assuming the vector always has elements.

  1. In the return statement, should be i+1 instead of i++:

return max(integer_array[i], find_max(integer_array, i+1));.

The problem with i++ is that this form would pass the value i to find_max for the second argument, and then increment. So you end up calling either return max(integer_array[i], find_max(integer_array, i)) or return max(integer_array[i+1], find_max(integer_array, i)), I forgot if the parameters were evaluated in order or not. In either case, it would not finish correctly.

  1. Also I would suggest const ref for find_max 1st argument:

int find_max(const vector<int> &integer_array, int i). Otherwise it would copy the integer_array again and again without needing to modify the content. see reference.

  1. Thanks for the comment from paddy, very helpful in my future drafting answers.

Upvotes: 1

Related Questions