This is a C program with the recursive binary search algorithm, however when I run it, the debugger says there is an access segmentation fault in the binary search function. Why is this and how do I fix this?
Here is the recursive binary search function:
int binSearch(int val, int numbers[], int low, int high)
{
int mid;
mid=(low+high)/2;
if(val==numbers[mid])
{
return(mid);
}
else if(val<numbers[mid])
{
return(binSearch(val, numbers, low, mid-1));
}
else if(val>numbers[mid])
{
return(binSearch(val, numbers, mid+1, high));
}
else if(low==high)
{
return(-1);
}
}
Thank you :)
您必须在val < ...
和val > ...
之前检查low == high
,因为否则high
可能变得小于low
,因此您的下一个递归可能会计算出无效的mid
Your edge cases are off: specifically, when your low
and high
indices pass, you continue to call recursively before you reach the low == high
test. Rearrange the tests:
int binSearch(int val, int numbers[], int low, int high) {
int mid = (low + high) / 2;
if (val == numbers[mid]) return mid;
if (val < numbers[mid]) {
if (mid > low) return binSearch(val, numbers, low, mid-1);
} else if (val > numbers[mid]) {
if (mid < high) return binSearch(val, numbers, mid+1, high);
}
return -1;
}
Try this:
Fixed if constructs in your code
int binSearch(int val, int numbers[], int low, int high)
{
int mid;
mid=(low+high)/2;
if(low<=high)
{
if(val==numbers[mid])
return mid;
else if(val<numbers[mid])
return binSearch(val, numbers, low, mid-1);
else
return binSearch(val, numbers, mid+1, high);
}
else
return -1;
}
low
< high
is not ensure. If that is not the case your are going to search out of the array bound.
Add a sanity check for that.
if (low < high)
return -1;
EDIT: as other point out you can also check if low == high at the beginning but that does not ensure that the first call of the function have sound value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.