I made a program that calculates the maximum value of an array using the divide and conquer algorithm, but the output is 0.
#include <iostream>
using namespace std;
int array[50];
void maximum(int index1, int index2, int&max_number) {
int max_number1;
int max_number2;
int half;
if (index1 == index2)
max_number = array[index1];
else {
half = (index1 + index2) / 2;
maximum(index1, half, max_number1);
maximum(half + 1, index2, max_number2);
if(max_number1 < max_number2)
max_number = max_number2;
else
max_number = max_number1;
}
}
int main() {
int index1;
int index2;
int max_number = 0;
cout << "index2 = ";
cin >> index2;
for (index1 = 0; index1 < index2; index1++)
cin >> array[index1];
maximum(index1, index2, max_number);
cout << "maximum number = " << max_number;
return 0;
}
What should I do?
you have a typo in this part of code
for(index1 = 0; index1 < index2; index1++)
index1 will increased till to index2, and then
maximum(index1, index2, max_number);
will pass the same the same values in the 1st/2nd parameter, you may change the code like as
for(index1 = 0; index1 < index2; index1++)
cin>>array[index1];
index1 = 0;
maximum(index1, index2, max_number);