感覺是不是我眼龊了哪裡沒看清楚,mid最後一次的值時2,然後return mid,result得到的卻是1,為什麼?
#include<stdio.h>
int binary_Search(int a[],int low,int high,int key){
if(low>high) return -1;
else{
int mid=low+(high-low)/2;
printf("low=%d,mid=%d,high=%d\n",low,mid,high);
if(a[mid]==key) {
printf("a[mid]=%d,mid=%d\n",a[mid],mid);
return mid;
}
if(a[mid]<key)
binary_Search(a,mid+1,high,key);
if(a[mid]>key)
binary_Search(a,low,mid-1,key);
}
}
int main(){
int a[]={0,1,2,3,4,5,6,7,9,10,11,12,13,14,15,16};
int result;
result=binary_Search(a,0,16,2);
printf("result=%d\n",result);
return 0;
}
很明顯的錯誤嘛~
if(a[mid]key) return binary_Search(a,low,mid-1,key);