我编写了一个用于二进制搜索的递归程序,如您所见,我试图在给定数组中查找目标= 21的位置,这将使我的位置返回2。但是我的输出是1。在调试时,它与att匹配arr [start] = target,但是直接跳到了findTheNumber(arr,mid + 1,end,target)行;然后下一行,然后返回中点。.想知道为什么我的返回在“返回起点”处中断]
package Recursion;
public class BinarySearch {
static int mid = 0;
public static int findTheNumber(int[] arr, int start, int end, int target) {
if (arr[start] == target) {
return start;
}
mid = (start + end) / 2;
if (arr[mid] == target) {
return mid;
}
if (target >arr[mid]) {
findTheNumber(arr, mid + 1, end, target);
} else if (target <arr[mid]) {
findTheNumber(arr, start, mid-1, target);
}
return mid;
}
public static void main(String[] args) {
int[] arr = { 10, 12,21 };
int start = 0;
int end = arr.length - 1;
int target = 21;
System.out.println(findTheNumber(arr, start, end, target));
}
}
if (target >arr[mid]) {
findTheNumber(arr, mid + 1, end, target);
} else if (target <arr[mid]) {
findTheNumber(arr, start, mid-1, target);
}
您只是在此处返回mid
点,而不是递归调用的实际结果。您的代码应类似于:
if (target >arr[mid]) {
return findTheNumber(arr, mid + 1, end, target);
} else if (target <arr[mid]) {
return findTheNumber(arr, start, mid-1, target);
}