我只允许使用给定的参数。我无法想象找到目标的索引。有什么想法吗?
#include <stdio.h>
int RecBinarySearch(int arr[], int len, int target) {
if (len <= 0)
return 0;
int mid = len/2;
if (target == arr[mid]){
return 1;
}
if (target < arr[mid]){
int i=0;
return RecBinarySearch(arr, mid, target);
}
else {
return RecBinarySearch(arr+mid+1, len-mid-1, target);
}
}
int main(void){
int arr[6]={1,2,3,4,5,6};
int len=sizeof(arr)/sizeof(arr[0]);
int target = 5;
RecBinarySearch(arr,len,target);
}
答案 0 :(得分:1)
第二:你不应该返回0或1,你不应该返回mid或-1如果没有找到,并且因为你在递归调用中移动了数组(传递数组+ mid + 1) ,你应该将shift值添加到返回值,然后在main中返回值中的位置。
答案 1 :(得分:1)
#include <stdio.h>
int RecBinarySearch(int arr[], int len, int target) {
if(len <= 0) return -1;
int mid = len / 2;
if(arr[mid] == target) return mid;
if(arr[mid] < target) {
int rightIndex = RecBinarySearch(arr+mid+1, len-mid-1, target);
return rightIndex == -1 ? -1 : mid+rightIndex+1;
} else {
int leftIndex = RecBinarySearch(arr, mid, target);
return leftIndex == -1 ? -1 : leftIndex;
}
}
int main(void){
int arr[6]={1,2,3,4,5,6};
int len=sizeof(arr)/sizeof(arr[0]);
int target = 5;
printf("%d", RecBinarySearch(arr,len,target));
}
答案 2 :(得分:1)
鉴于此,我只允许使用给定的参数,您可以使用以下内容。看到它正常工作here:
int BinarySearch(int arr[], int len, int target) {
int startI = 0, endI = len-1;
while(startI<=endI)
{
int mid= (startI+endI)/2;
if(arr[mid] == target)
return mid;
if(arr[mid] < target)
{
startI = mid +1;
}
else
{
endI = mid -1;
}
}
return -1;
}