我是新來編程和編寫代碼遞歸二進制搜索,但輸出是錯誤的。
我試着調試過很多次,但不知道自己出錯的地方。錯誤的結果在二進制搜索在Java
public class Number {
public static void main (String[] args){
int []a = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
int key = 7;
int mid,low,high;
low=0;
high=a.length-1;
int pos=binarySearch(a,key,low,high);
System.out.println(key +" is found at "+pos+" position");
}
public static int binarySearch(int[]a,int key,int low, int high) {
int mid=(low+high)/2;
if(key<a[mid]){
high=mid-1;
binarySearch(a,key,low,high);
}
else if(key >a[mid]){
low=mid+1;
binarySearch(a,key,low,high);
}
else if(low>high){
return -1;
}
return mid;
}
}
輸出是什麼? – dnuka
非常感謝。遞歸調用之前添加return關鍵字解決了它。 – asritha