#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int arr[10]={0};
int binary_search(int d,int *arr,int m,int n){
if(n<=m) return d==arr[n]?n:-1;
else{
if(d>arr[(n+m)/2]) return binary_search(d,arr,(n+m)/2+1,n);
if(d==arr[(n+m)/2]) return (n+m)/2;
else return binary_search(d,arr,m,(n+m)/2);
}
return -1;
}
int main(void){
srand(time(0));
for(int i=0;i<10;i++){
arr[i]=arr[i-1]+rand()%10;
printf("%d ",arr[i]);
}
printf("\n");
int d=0;
while(scanf("%d",&d)!=EOF){
int n=binary_search(d,arr,0,9);
if(n!=-1) printf("%d has been find in arr[%d]\n",d,n);
else printf("%d not find\n",d);
}
return 0;
}
二分查找算法
于 2024-09-11 10:45:48 首次发布