/*二分查找*/
#include<stdio.h>
int Bsearch(int* p, int n, int x);/*函数声明*/
int main()
{
int a[10] = { 1,2,3,4,5,6,7,8,9,0 };/*有序数组*/
int x, m;
printf("Enter x:");/*提示输入*/
scanf_s("%d", &x);
m = Bsearch(a, 10, x);
if (m >= 0)
printf("Index is %d\n", m);
else
printf("Not found\n");
return 0;
}
int Bsearch(int* p, int n, int x)/*二分查找函数3*/
{
int high, low, mid;
low = 0; high = n-1;/*开始时查找区间为整个数组*/
while (low <= high) {/*循环条件*/
mid = (low + high) / 2;/*中间位置*/
if (x == p[mid])
break;
else if (x < p[mid])
high = mid - 1;/*前半段,high前移*/
else
low = mid + 1;/*后半段,low后移*/
}
if (low <= high)
return mid;/*找到返回下标*/
else
return -1;/*找不到返回-1*/
}
二分查找示例
最新推荐文章于 2024-03-13 14:52:22 发布