二分查找递归实现和非递归实现
程序员文章站
2024-03-19 15:37:10
...
#include<stdio.h>
#include<stdlib.h>
# define N 10
/*二分查找,非递归,数组必须有序
*/
int Bsearch(int data[],int start,int end,int value ){
while(start<=end){
int mid=(start+end)/2;
if(data[mid]==value)
return mid+1;
else if(data[mid]>value){
end=mid;
}
else if(data[mid]<value){
start=mid+1;
}
}return -1;
}
/*
二分查找,递归实现
int Bsearch(int data[],int start,int end,int value ){
int mid=(start+end)/2;
if(start<end){
if (data[mid]==value)
return mid+1;
else if (data[mid]>value)
return Bsearch(data,start,mid,value);
else
return Bsearch(data,mid+1,end,value);
}
else
return -1;
}*/
void pri(int data[]){
for (int i=0;i<N;i++){
printf("%d \n",data[i]);
}
printf("\n");
}
int main(){
int value,result;
int data[N]={1,2,4,5,8,9,12,15,26,30};
pri(data);
printf("请输入要查找的值\n");
scanf("%d",&value);
result=Bsearch(data,0,N,value);
printf("%d\n",result);
system("pause");
}