#include <stdio.h>
#include <stdlib.h>
int cmpfunc (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int Biserch(int key,int n,int values[])
{
int L = 0,R = n - 1,mid;
while(L < R)
{
mid = (L + R) >> 1;//二进制向左移位1
if(values[mid] == key)return mid;
else if(values[mid] < key)L = mid + 1;
else R = mid - 1;
}
return -1;
}
int main(int argc, char const *argv[]) {
int n,i,key;
printf("请输入数列长度:");
scanf("%d",&n);
int values[n];
printf("请输入%d个数:\n",n);
for(i = 0;i < n;i++)
{
scanf("%d",&values[i]);
}
qsort(values, n, sizeof(int), cmpfunc);
printf("请输入查找得数字:");
scanf("%d",&key);
int pos = Biserch(key,n,values);
if(pos == -1)printf("没有找到!\n");
else printf("查找成功!\n");
return 0;
}
王道考研 ++++ 二分查找
最新推荐文章于 2024-06-11 09:15:00 发布