问题
public static int binarySearch(double[] arr, int low, int high, double inq){
int mid = (low + high)/2;
if(arr == null) return -1;
if(low > high) return -1;
if(arr[(int)inq] < arr[low])
return -1;
if(arr[(int)inq] > arr[high])
return -1;
}
I am suppose to search through the array arr recursively to find the index of inq. All I have is the termination cases. Not sure how to go about this problem.
The original question is this one:
search the array slice arr[low:high] for an occurrence
of inq. If inq occurs in arr, return an index i such that
arr[i] == inq. Otherwise, return -1. Assume that arr is sorted in increasing order.
And these are the answers to some cases:
The input array is table = { 2, 4, 6, 8, 10, 12, 14 }.
- 2 was found in table[0:6] at index 0
- 3 was found in table[0:6] at index -1
- 4 was found in table[2:6] at index -1
- 12 was found in table[2:5] at index 5
I know how to do it using iterations, but I am new to recursive methods. I'd appreciate any help on this.
回答1:
The key is to update the search range by updating low and high by passing the modified low and high into the next recursive call. Each call, we update the search range to either [low, mid-1] or [mid+1, high] depending on comparison between inq and arr[mid]
This will work:
public static int binarySearch(double[] arr, int low, int high, double inq){
int mid = (low + high)/2;
if(arr == null || low > high) return -1;
if(arr[mid] == inq) return mid;
if(arr[mid] < inq) { // inq is in the upper half
return binarySearch(arr, mid+1, high, inq);
}
if(arr[mid] > inq) { // inq is in the lower half
return binarySearch(arr, low, mid-1, inq);
}
}
来源:https://stackoverflow.com/questions/33599061/binary-search-using-recursion