angchan, upon further inspection, it seems you've misunderstood how the algorithm works, and so have run into a bunch of issues. Biggest mistakes were that you:
1. thought the array was getting smaller over time, which isn't true. The input array never changes; only the indices do.
2. were sending elements of the vector to the recursive function calls instead of sending indices.
3. had loops in the function. The function is supposed to call itself -- this is how it progresses and how it ends (with base cases). Doesn't need loops inside.
I'll explain it to you with
i being the left index, and
j the right index. These are the variables often used for indices in array algorithms like this. Suppose array is
vector<int> v = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; |
We start by setting i to the starting
index, and j to last
index. This is a 10-element array, so
i=0, j=9. Middle is (i+j)/2, or 4 with integer division.
1. We always choose (i, middle) for lower range.
2. We always choose (middle+1, j) for upper range.
3. Return max(lower range, upper range).
Hint: use std::max
!
Base cases:
1. When i==j we have a single element, so just return v[i]
2. When j-i==1 we have a difference of one, aka two elements; return max(v[i], v[j])
10, 9, 8, 7, 6, 5, 4, 3, 2, 1
i=0 j=9
mid=4
10, 9, 8, 7, 6 5, 4, 3, 2, 1
i=0 j=4 i=5 j=9
mid=2 mid=7
10, 9, 8 7, 6 5, 4, 3 2, 1
i=0 j=2 i=3 j=4 i=5 j=7 i=8,j=9
return max(7,6) return max(2,1)
mid=1 mid=6
10, 9 8 5, 4 3
i=0 j=1 i=2 j=2 i=5 j=6 i=7 j=7
max(10,9) return 8 max(5,4) return 3
return 10 return 5
|
So code should look like this:
1 2 3 4 5 6 7 8 9 10 11 12
|
// Finds max using recursion and divide+conquer on a vector range
// i - index from the left
// j - index from the right
int MaxConquer(const vector<int>& v, int i, int j)
{
if (i == j) { return v[i]; }
if (j-i == 1) { return max(v[i], v[j]); }
int mid = (i+j)/2;
return max( MaxConquer( v, i, mid ),
MaxConquer( v, mid+1, j ) );
}
|
1 2 3 4 5 6
|
int main()
{
vector<int> v = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
cout << "Maximum is: "<< MaxConquer(v, 0, v.size()-1) << endl;
return 0;
}
|