I'm implementing a binary search and the code is below, however, it doesn't print out the right answer buy it prints out correct answer inside the function body, so it makes me really confused.
#include <iostream>
using namespace std;
int research(int a[], int target, int lowIndex, int highIndex)
{
int finalIndex;
cout << lowIndex << " " << highIndex << endl;
int midIndex = (lowIndex + highIndex) / 2;
if (a[midIndex] == target)
{
finalIndex = midIndex;
cout << "The final index is: " << finalIndex << endl;
}
else
{
if (a[midIndex] < target)
{
research(a, target, midIndex + 1, highIndex);
}
else
{
research(a, target, lowIndex, midIndex - 1);
}
}
return finalIndex;
}
int main()
{
int* array = new int[1000];
for (int i = 0; i < 1000; i++)
{
array[i] = i + 1;
}
cout << research(array, 234, 0, 999) << endl;
return 0;
}
The line:
cout << "The final index is: " << finalIndex << endl;
prints out the right final index but the line
cout << research(array, 234, 0, 999) << endl;
doesn't, instead it prints out random number. Anyone know what is going wrong here? Thank you!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…