c-二进制搜索结果非常不一致



为学校做一个编码练习,我们必须使用二进制搜索来查找数组中值的位置。输出应该生成索引位置。

当测试它时;命中和未命中";。有时它会说,当有一个价值时,其他时候,当一个价值明显存在时,它会想出";元素不存在于数组"中;。正在努力排除这种不一致性的来源。

如有任何帮助/提示/建议,我们将不胜感激。

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define SIZE 10
int binarySearch(int array[], int starting, int ending, int searchKey)
{
if (ending >= starting)
{       
int mid = starting + (ending - starting)/2;
if (array[mid] == searchKey) return mid;
if (array[mid] > searchKey) return binarySearch(array, starting, mid-1, searchKey);
return binarySearch(array, mid+1, ending, searchKey);
}
return -1;
}
int main(void)
{
int array[10],i;
int searchKey;
srand(time(NULL));
for (i=0; i<10; i++)
array[i]=rand()%100;
printf("Array before sorting n");
for (i=0; i<10; i++)
printf("%d n", array[i]);

printf("Enter a number to searchn");
scanf("%d", &searchKey);
int result = binarySearch(array, 0, SIZE-1, searchKey);
(result == -1)? 
//Displaying the results to the user
printf("Element is not present in array")
: printf("Element is present at index %d", result+1);

return 0;
}

二进制搜索要求对数组进行排序。

参见例如。https://en.wikipedia.org/wiki/Binary_search_algorithm#:~:text=Binary%20搜索%20工作%20在%20排序,在%20数组的%20下半%20。

上面写着:

在计算机科学中,二进制搜索,也称为。。。。,是一种搜索算法,用于查找排序数组中目标值的位置

您通过执行以下操作生成数组:

for (i=0; i<10; i++)
array[i]=rand()%100;

所以它显然不是一个排序数组。因此,二进制搜索将不起作用。

你可以在数组上使用qsort对其进行排序。如果你不允许更改数组,你将需要另一种搜索算法,而不是二进制搜索。

在应用二进制搜索之前,需要按递增/递减顺序对数组进行排序。

最新更新