C语言习题3
程序员文章站
2022-07-15 16:27:58
...
在一个有序数组中查找具体的某个数字n。 编写int binsearch(int x, int v[], int n); 功能:在v[0]
<=v[1]<=v[2]<= ....<=v[n-1]的数组中查找x.
择半查找算法/二分查找算法:
#include <stdio.h>
int main()
{
int number[10] = {1,2,3,4,5,6,7,8,9,10};
int sz = sizeof(number)/sizeof(number[0]);
int left = 0;
int right = sz-1;
int x = 7;
int mid;
for(;left<=right;)
{
mid = (left+right)/2;
if(number[mid]<x)
{
left = mid + 1;
}
else if(number[mid]>x)
{
right = mid - 1;
}
else
{
printf("找到了,下标是%d\n",mid);
break;
}
}
if(number[mid] != x)
printf("没有找到\n");
return 0;
}
上一篇: 判断括号是否匹配
下一篇: PHP 表单验证 - 必填字段