【问题标题】:Binary search in C using recursive function with return type使用具有返回类型的递归函数在 C 中进行二进制搜索
【发布时间】:2013-10-19 18:13:03
【问题描述】:

下面,我正在尝试使用递归函数编写一个简单的二进制搜索程序。当我运行它时,它会将要搜索的数组和键作为输入,但之后编译器会突然停止。可能是因为某处的无限循环。

#include<stdio.h>
int present_flag;
int binary_search(int array[],int low,int high,int key)
{
int mid=(high + low)/2;
if(low<=high)
{
    if (array[mid] == key)
    {
    printf("Key found at index %d \n",mid);
    return 1;
    }
        else if (array[mid] >key)
        return 0+binary_search(array,low,mid,key);
            else 
            return 0+binary_search(array,mid+1,high,key);;
}
else return 0;
}
main()
{
int array[9],i,n,key;
printf("Enter 9 numbers in asc order \n");
for(i=0;i<9;i++)
scanf("%d",&n);
printf("Enter number to be searched\n");
scanf("%d",&key);
present_flag=binary_search(array,0,8,key);
if (present_flag==0 )
printf("Number not present in array\n");
}

【问题讨论】:

  • 它是怎么开始运行然后编译器停止的?你是不是和那个挖掘机搞混了?
  • 只是想知道:您是否意识到您的数组从未被填充,因为您只是将输入存储在 n 9 次以上?请帮自己(和我们)一个忙:正确缩进代码。
  • 你为什么要加零加binary_search()返回值?

标签: c recursion binary-search-tree infinite-loop


【解决方案1】:

先填写array

修复:

for(i=0;i<9;i++) //Assuming your n is 9
  scanf("%d",&array[i]);
              ^^^ not n

【讨论】:

    【解决方案2】:
    class BinarySearch
    {
    // Returns index of x if it is present in arr[], else
    // return -1
    int binarySearch(int arr[], int x)
    {
        int l = 0, r = arr.length - 1;
        while (l <= r)
        {
            int m = l + (r-l)/2;
    
            // Check if x is present at mid
            if (arr[m] == x)
                return m;
    
            // If x greater, ignore left half
            if (arr[m] < x)
                l = m + 1;
    
            // If x is smaller, ignore right half
            else
                r = m - 1;
        }
    
        // if we reach here, then element was not present
        return -1;
    }
    

    欲了解更多信息, http://www.geeksforgeeks.org/binary-search/

    【讨论】:

      【解决方案3】:

      首先它不是被阻止的compiler。编译器仅将您的程序转换为机器级指令。

      其次,递归调用不会停止。因为您没有准确指定终止条件。因此,您的程序无限期地是executing,直到它用完堆栈空间并以segmentation fault 结束。

      修正后的代码如下(我在cmets程序中指定了改动):

      #include<stdio.h>
      int present_flag;
      int binary_search(int array[],int low,int high,int key)
      {
      
      if(low==high)//if boundaries are same, just compare with the value and return
                   //appropriately...
      {
          if(array[low]==key){
          printf("Key found at index %d \n",low);
          return 1;
      }
      else
      return 0;
      }
      int mid=(high + low)/2;
      if(low<high)
      {
          if (array[mid] == key)
          {
          printf("Key found at index %d \n",mid);
          return 1;
          }
              else if (array[mid] >key)
              return binary_search(array,low,mid,key);//need not put a zero explicitly...
                  else 
                  return binary_search(array,mid+1,high,key);
      }
      else return 0;
      }
      main()
      {
      int array[9],i,n,key;
      printf("Enter 9 numbers in asc order \n");
      for(i=0;i<9;i++)
      scanf("%d",&array[i]);// <--- this should be array[i] and not n. 
      printf("Enter number to be searched\n");
      scanf("%d",&key);
      present_flag=binary_search(array,0,8,key);
      if (present_flag==0 )
      printf("Number not present in array\n");
      }
      

      以我们得到的更简化的方式重写函数:

      int binary_search(int array[],int low,int high,int key)
      {
          int mid=(high + low)/2;
          if (array[mid] == key)
          {
              printf("Key found at index %d \n",mid);
              return 1;
          }
          if(low<high)
          {
              if(array[mid] >key)
                return binary_search(array,low,mid,key);
              else 
                return binary_search(array,mid+1,high,key);
          }
          return 0;
      }
      

      【讨论】:

      • 你不需要写整个程序,告诉实现就好了。那更好
      【解决方案4】:

      针对 nitish712 的简化版代码,我们可以进一步简化代码的另一种方法是简单地返回 -1(而不是在元素不存在的情况下返回 0),并在元素不存在时返回 mid 本身存在:

      int binary_search(int array[],int low,int high,int key)
      {
      int mid=(high + low)/2;
      if (array[mid] == key)
      {
      
          return mid;//This value can be utilized elsewhere in the code to check availability of the key in the array
      }
      if(low<high)
      {
          if(array[mid] >key)
            return binary_search(array,low,mid,key);
          else 
            return binary_search(array,mid+1,high,key);
      }
      return -1;
      }
      

      【讨论】:

        【解决方案5】:

        下面的代码sn-p是二分查找的简单实现,

        bool search_recursive(int value, int values[], int lower, int upper) 
        {
            if (lower > upper) return -1;
            int mid = (lower + upper) / 2;
        
            if (value == values[mid]) {
                return 1;
            }
        
            if (value > values[mid]) {
                // Search right half
                return search_recursive(value, values, mid + 1, upper);
            } else {
                // Search left half
                return search_recursive(value, values, lower, upper - 1);
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2014-11-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-03-31
          • 2021-04-28
          • 1970-01-01
          • 2022-08-02
          • 1970-01-01
          相关资源
          最近更新 更多