报错多次终于通过的折半查找,记录一下
#include <stdio.h>
#include <stdlib.h>
int BinSearch(int arr[],int len,int key);
int main() {
int n;
int k;
int num[1000001];
int mem[1000001];
int i,j;
// 反复读入数字和查找数字的数量
while (scanf("%d%d", &n, &k) != EOF) {
//mem = (int*)malloc(k);
//num = (int*)malloc(n);
// 读入给定的数字
for (i = 0; i < n; i++) {
scanf("%d", &num[i]);
}
for (j = 0; j < k; j++) {
// 读入待查找的数字,
scanf("%d", &mem[j]);
}
}
for(j = 0 ; j < k ; j ++){
printf("%d",BinSearch(num,n,mem[j]));
if(j < k - 1){
printf(" ");
}
}
return 0;
}
//·······································
int BinSearch(int num[],int len,int key)
{
int low=0; //定义初始最小
int high=len-1; //定义初始最大
int mid; //定义中间值
while(low<=high)
{
mid=(low+high)/2; //找中间值
if(key==num[mid]) //判断min与key是否相等
return mid + 1;
else if(key>num[mid]) //如果key>mid 则新区间为[mid+1,high]
low=mid+1;
else //如果key<mid 则新区间为[low,mid-1]
high=mid-1;
}
return 0; //如果数组中无目标值key,则返回 0 ;
}