我有以下代碼正在執行基於數組和值的二進制搜索以查找傳遞給函數。但是,當我進入函數時,數組沒有值。這是爲什麼發生?我看過,我相信在傳遞陣列方面一切都是正確的。傳遞給函數時數組爲空
#include <iostream>
using namespace std;
int binSearch(int [], int , int , int);
void main()
{
int a[10];
int low;
int high;
int searchValue;
for (int i = 0; i < 10; i++)
{
a[i] = i;
}
low = 0;
high = 9;
searchValue = 6;
int searchResult = binSearch(a, low, high, searchValue);
cout << searchResult << endl;
}
int binSearch(int a[], int low, int high, int searchValue)
{
int newHigh;
newHigh = (low + high)/2;
if (low > high)
{
return -1;
}
else if (high == low)
{
if (a[high] == searchValue)
{
return high;
}
else
{
return -1;
}
}
else if (a[newHigh] < searchValue)
{
return binSearch(a, low, newHigh, searchValue);
}
else
{
return binSearch(a, newHigh, high, searchValue);
}
}
_...數組有沒有值..._你怎麼發現? –
該數組確實有值,但是你的算法是錯誤的。 –
該數組用for循環賦值,然後傳遞。調試時,當它進入binSearch時,數組中不包含任何內容......所以算法放在一邊,它仍然沒有任何東西...... – cb1295