#define MAX 100
int n = 0;
int x[MAX];//seq data array {x[0] < ... x[max - 1]}
int binary(int t)
{
int l, u;
if(x[0] > t ||x[n] < t || n < 0){
printf("input error \n");
return -1;
}
l = 0;
u = n;
while (l <= m) {
m = (l + u) / 2;
if (x[m] < t) {
l = m + 1;
} else if (x[m] > t) {
u = m - 1;
} else { //find it
return m;
}
}
return -1;
}
int p[MAX]; //用于检验的数组顺序是打乱的
int main(void)
{
int i = 0;
printf("please input n( <%d)", MAX);
scanf("%d", &n);
for (i = 0; i < n;i++) {
if (-1 == binary(p[i])) {
printf("fail to find p[%d] = %d \n", i, p[%d]);
}
}
}
两分搜索算法(折半查找算法)
最新推荐文章于 2024-11-04 17:55:03 发布