【发布时间】:2016-08-31 04:11:55
【问题描述】:
我做了一个二分查找程序,在打印数组的索引值之前遇到了程序冻结的问题。
变量 high 用于最后一个索引,low 用于数组的第一个索引。
特此附上代码
// binary search
#include<stdio.h>
#include<conio.h>
int binary(int a[],int n,int x);
void main()
{
int arr[10];
int i,x,n,r;
clrscr();
printf("Enter number of data elements");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("Enter the element to be search");
scanf("%d",&x);
r=binary(arr,n,x);
if(r==-1)
{
printf("Not found");
}
else
{
printf("Found : %d",r);
}
getch();
}
int binary(int a[],int n,int x)
{
int high=n-1;
int low=0;
int result=-1,mid;
while(low<=high)
{
mid=(high+low)/2;
if(x==a[mid])
{
result=mid;
}
else if(x<a[mid])
{
high=mid-1;
}
else if(x>a[mid])
{
low=mid+1;
}
}
return (result);
}
【问题讨论】:
-
你做过任何基本调试吗?即使用调试器和/或调试打印语句来跟踪程序的执行?
-
在
binary中,您需要在找到搜索项时跳出循环。我用调试器花了 30 秒才找到它。 -
是的,我使用了while循环,最后我返回了最终结果
-
我想你不明白。您需要在
if(x==a[mid])块中使用break语句。
标签: c search binary-search