#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LEN 8
int halfind(int *a,int key)
{
int start =0,end=LEN-1,mid;
while(start <= end){
mid=(start+end)/2;
if(a[mid] > key){
end=mid -1;
}
else if(a[mid] < key){
start=mid+1;
}
else
return mid;
}
return -1;
}
int main(int argc,char **argv)
{
int a[]={1,2,3,4,5,6,7,8};
printf("%dn",halfind(a,atoi(argv[1])));
return 0;
}
==============递归方式===============
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LEN 8
int a[]={1,2,3,4,5,6,7,8};
int halfind(int start,int end,int key)
{
int mid;
if(start <= end){
mid=(start+end)/2;
if(a[mid] > key){
halfind(start,mid -1,key);
}
else if(a[mid] < key){
halfind(mid+1,end,key);
}
else{
printf("%dn",mid);
return mid;
}
}
return -1;
}
int main(int argc,char **argv)
{
printf("%dn",halfind(0,LEN-1,atoi(argv[1])));
return 0;
}