c - 递归二进制搜索函数缺少什么? (C)

标签 c function recursion binary-search

我正在尝试创建一个对排序数组进行二分查找的函数。我检查了一切,一切正常,除了一件事:

如果我没有在函数末尾放置一个 return 语句,没有被 If 包围,它就不会构建我的程序。如果我输入“return 0”,无论如何它都会返回 0。如果我对 1 做同样的事情,它总是会返回 1,而且我看不出我的问题在哪里。希望得到一些帮助。

#include <stdio.h>
#define N 4
int search_matrix(int a[N][N], int x);
int binsearch(int a[], int x, int low, int high);
int main(){
    int a[N][N];
    printf("Please Enter Matrix : \n");
    for(int i=0;i<N;i++){
        for(int j=0;j<N;j++){
            scanf("%d",&a[i][j]);
        }//forj
    }//fori
    printf("Please enter x : \n");
    int x;
    scanf("%d",&x);

    printf("%d\n",search_matrix(a,x));
    return 0;
}
int search_matrix(int a[N][N], int x){
    if(x>a[0][N-1]||x<a[N-1][0])
        return 0;

    int savedIndex=0;
    for(int i=0;i<N;i++){
        if(x>a[i][0]){
            savedIndex=i;
            break;
        }
    }//for

    return(binsearch(a[savedIndex],x,0,N));

}//search_matrix

//------- THE PROBLEMATIC FUNCTION! ---------
int binsearch(int a[], int x, int low, int high) {
   int mid;
   if (low > high)
      return 0;
   mid = (low + high) / 2;
    if (x == a[mid]) {
      return 1;
   } else if (x < a[mid]) {
      binsearch(a, x, low, mid - 1);
   } else {
      binsearch(a, x, mid + 1, high);
   }


}

最佳答案

检查一下:

    #include<stdio.h>
    #define N 4
    int search_matrix(int a[N][N], int x);
    int binsearch(int a[], int x, int low, int high);
    int main(){
        int a[N][N], i, j;
        printf("Please Enter Matrix : \n");
        for(i=0;i<N;i++){
            for(j=0;j<N;j++){
                scanf("%d",&a[i][j]);
            }//forj
        }//fori
        printf("Please enter x : \n");
        int x;
        scanf("%d",&x);

        printf("%d\n",search_matrix(a,x));
        return 0;
    }
    int search_matrix(int a[N][N], int x){
        if(x>a[0][N-1]||x<a[N-1][0])
            return 0;

        int savedIndex=0, i;
        for(i=0;i<N;i++){
            if(x>a[i][0]){
                savedIndex=i;
                break;
            }
        }//for

        return(binsearch(a[savedIndex],x,0,N));

    }//search_matrix

    //------- THE PROBLEMATIC FUNCTION! ---------
    int binsearch(int a[], int x, int low, int high) {
       int mid;
       if (low > high)
          return 0;
       mid = (low + high) / 2;
        if (x == a[mid]) {
          return 1;
       } else if (x < a[mid]) {
          binsearch(a, x, low, mid - 1);
       } else {
          binsearch(a, x, mid + 1, high);
       }


    }

关于c - 递归二进制搜索函数缺少什么? (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41836498/

相关文章:

c - AVR ATmega 在主循环之前使用 printf 时不断重置

function - Postgresql:将输入键/值对转储到 PL/pgSQL 中的字符串变量中

javascript - 调用不带括号的函数javascript

algorithm - 无法理解用两个不同的输入递归调用相同的方法

scala - 在对象而非类上定义时,方法是尾部递归

c++ - 试图在递归函数 : Unhandled exception/Stack overflow 中捕获失败的分配

c - Openmp并行循环

c - 将给定链表的反向存储到另一个链表中

c - neighbors.c程序调试(多维数组)

c# - 使用 HttpTrigger 属性在 Azure 函数中自定义路由