2017-01-24 9 views
1

ソートされた配列に対してバイナリ検索を実行する関数を作成しようとしています。私はすべてをチェックしたが、1つを除いてすべて正常に動作する:再帰バイナリ検索機能に何か不足していますか? (C)

Ifのに囲まれていない関数の最後にreturn文を置かないと、プログラムがビルドされない。私が '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); 
    } 


} 
+1

'binsearch(、X、低、中 - 1);' - > 'リターンbinsearch(、X、低、中を - 1); ' – BLUEPIXY

答えて

0

それをチェックアウト:

#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); 
     } 


    } 
関連する問題