简体   繁体   English

C语言中递归二进制搜索算法中的分割错误

[英]Segmentation fault in recursive Binary Search Algorithm in C

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. 这是一个具有递归二进制搜索算法的C程序,但是当我运行它时,调试器说二进制搜索功能中存在访问分段错误。 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. 您的极端情况不对:特别是,当您的lowhigh指数通过时,您会在达到low == high测试之前继续递归调用。 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. low < high不确定。 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. 编辑:正如其他指出的那样,您还可以在开始时检查低==高,但是不能确保函数的第一次调用具有声音值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM