Home > database >  Finding the maximum value in a vector using recursion C
Finding the maximum value in a vector using recursion C

Time:09-16

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...

CodePudding user response:

I am assuming the vector always has elements.

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

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

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

int find_max(const vector<int> &integer_array, int i).

  • Related