1

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

3
  • 1
    The value of i++ is i. Change i++ to i + 1. Commented Sep 16, 2021 at 1:54
  • using recursion -- How many items in the vector? If there are thousands of items, you are risking blowing out the stack memory using recursion. And why use such an unorthodox way (recursion) to find the maximum value? There are valid reasons to use recursion, like tree traversal, but to find the max item in a vector?? Commented Sep 16, 2021 at 2:04
  • O(N^2) storage complexity + O(N) stack overhead... It's almost like you're trying to find the least efficient way to do this. Commented Sep 16, 2021 at 2:19

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

3 Comments

Avoid instructing what to do without also saying why. Your "suggestion" actually touches on a super-important topic in C++. The way this algorithm has been written is devastating for both performance and memory overhead. You should describe the difference this small bit of syntax would make and why it's important.
Thanks for the help! Is it because i++ doesn’t update until later?
Yes that's right.

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.