您的位置:首页 > 其它

二分查找 (循环、递归两种方法)

2017-10-23 10:35 597 查看

二分查找 (binary search)

循环实现

int BinarySearch(int *a,int len,int target)
{
int low,high,mid;
low=0;
high=len-1;
while (low<=high) {
mid=(low+high)/2;
if (a[mid]==target)
return mid+1;
else if(a[mid]<target)
low=mid+1;
else if (a[mid]>target)
high=mid-1;
}
return NOTFOUND;
}

递归实现

int IterBiSearch(int *a, const int x, int begin, int end)
{
int mid;
mid = (begin + end) / 2;
if (x == a[mid])
return mid+1;
else if (x < a[mid])
return IterBiSearch(a, x, begin, mid - 1);
else if (x > a[mid])
return IterBiSearch(a, x, mid + 1, end);
return NOTFOUND;
}

主函数测试

int main() {
int A[]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
int toFind;
scanf("%d",&toFind);
int length=sizeof(A)/sizeof(*A);
//int result=(BinarySearch(A,length,toFind));
int result=IterBiSearch(A, toFind, 0, length-1);
switch (result%10)
{
case 1:
printf("%d is the %dst element of the sequence.\n",toFind,result);
break;
case 2:
printf("%d is the %ded element of the sequence.\n",toFind,result);
break;
case 3:
printf("%d is the %drd element of the sequence.\n",toFind,result);
break;
case -1:
printf("Can't find %d",toFind);
default:
printf("%d is the %dth element of the sequence.\n",toFind,result);
break;
}
return 0;
}

运行结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: