我正在尝试解决二进制搜索的 Spoj 问题,但我不断得到“错误答案”并且我看不到我的问题。这是我的搜索功能:
int binarySearch(int numbers[], int size, int key)
{
int start = 0;
int end = size - 1;
int middle;
while(start <= end)
{
middle = start + (end - start)/2;
if(key < numbers[middle])
end = middle - 1;
else if(key > numbers[middle])
start = middle + 1;
else
return middle;
}
return -1;
}
这是我的主要功能
int main()
{
int *numbers;
int n_numbers, n_queries, key, i, found;
scanf("%d %d", &n_numbers, &n_queries);
numbers = (int*)malloc(n_numbers * sizeof(int));
for(i = 0; i<n_numbers; i++)
scanf("%d", &numbers[i]);
for(i = 0; i<n_queries; i++)
{
scanf("%d", &key);
found = binarySearch(numbers, n_numbers, key);
printf("%d\n", found);
}
return 0;
}
这是 SPOJ 问题: http ://www.spoj.com/problems/BSEARCH1/