【发布时间】:2015-04-18 15:50:12
【问题描述】:
我一直在开发一个使用二进制搜索来搜索元素的程序,但是每次运行该程序时,我都会收到超出时间限制的错误。虽然我搜索了这个错误但我无法找到这个程序中的错误是什么请帮助这里是代码
#include<stdio.h>
int BinarySearch(int low,int high,int *a,int item);
int main(){
int a[50] , i , low , high , n , item , position;
printf("Enter the number of Elements");
scanf("%i",&n);
for(i=0;i<n;i++){
scanf("%i",&a[i]);
}
printf("Enter the Element to be searched");
scanf("%i",&item);
low=0;
high=n-1;
position=BinarySearch(low,high,a,item);
if(position==-1)
printf("Item not found");
else
printf("item was found on the %i position",position);
return 0;
}
int BinarySearch(int low,int high,int *a,int item){
int mid,loc,flag=0;
while (item!= a[mid] && low <= high)
{
mid = (low + high) / 2;
if(a[mid]==item){
loc=mid;
flag=flag+1;
}
else if (item < a[mid])
high = mid - 1;
else
low = mid + 1;
}
if (flag>=1)
return loc;
else
return -1;
}
【问题讨论】:
-
你正在使用
mid在BinarySearch()中未初始化