【发布时间】:2021-04-27 15:07:04
【问题描述】:
在学校进行编码练习,我们必须利用二分搜索来查找数组中值的位置。输出应生成索引位置。
在测试它时,它非常“碰碰运气”。有时它会说当一个值存在时,其他时候当一个值明显存在时它会提出“元素不存在于数组中”。正在努力排除这种不一致的根源。
任何帮助/提示/建议将不胜感激。
#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 search\n");
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;
}
【问题讨论】:
-
请添加“错过”的示例。并修复代码缩进。
-
输入是否排序?这是二进制搜索工作的必要条件。
-
请不要使用三元条件表达式而不是普通的
if else语句。它会让你的代码更难阅读和理解。 -
你在哪里排序你的数组?
-
确保数组已排序,因为二进制搜索适用于已排序的数组。
标签: c binary-search