close
#include<stdio.h>
int binary_search(int list[], int left, int right, int key);
int main(void)
{
int left,right,mid,key;
int found=0;// -1:not found
int num[]={5,12,34,56,76,81,99,123,145,168};
printf("Please input a int:\n");
scanf("%d",&key);
left=0;
right=9;
found=binary_search(num,left,right,key);
if(found>=0){
printf("The Key:%d is at Position:%d\n",key,found);
}else{
printf("Data not Found\n");
}
return 0;
}
int binary_search(int list[], int left, int right, int key)
{
int mid=(left+right)/2;
if(left<=right)
{
if(key==list[mid])
return(mid);
else if(key>list[mid])
return(binary_search(list,mid+1,right,key));
else
return(binary_search(list,left,mid-1,key));
}else
return(-1);
}
全站熱搜
留言列表