2015-01-18 5 views
1

알고리즘은 결과를 찾아서 true를 테스트하지만 값을 반환하지 않고 -2를 반환합니다. 왜 아무도 알지 못해? 나는 그것을 알아낼 수 없었다. (= 내 입력 $) : 여기 return 문이 실행되지 않는 이유는 무엇입니까? 이진 검색

int recursiveBinarySearch(int* a, int p, int r, int x){ 

    if(p>r){ 
     return -1; 
    }else{ 
     int m = (p+r)/2; 
     cout<<(a[m]==x)<<endl; 
     if(a[m]==x){ 
      cout<<"entering"<<endl; 
      return (m+1); 
      cout<<"wtf?"<<endl; 
      }else if(x<a[m]){ 
       recursiveBinarySearch(a,p,m-1,x); 
       }else if(x>a[m]) recursiveBinarySearch(a,m+1, r,x); 

    } 
    return -2; 

} 

이 출력됩니다 : 여기 코드, 당신은 재귀 recursiveBinarySearch()를 호출 할 때

>>$./a.out 
>>Type the number of slots 
>>$100 
>>Type a number to search for 
>>$40 
>>0 
>>0 
>>0 
>>0 
>>0 
>>1 
>>entering 
>>The search did not return any item-2 
+1

어떤 함수 반환에 대해 생각 . 재귀 호출이 끝나면 코드 경로를 살펴보십시오. – Mat

+1

return 문이 존재하지 않기 때문에 실행되지 않습니다. – immibis

답변

1

, 당신은 return 문 호출 재귀 경우 때문에 함수가 무언가를 반환하면 재귀 함수를 호출하는 함수는 같은 값을 반환해야합니다.

코드가 있어야한다 :

int recursiveBinarySearch(int* a, int p, int r, int x) 
{ 
if(p>r) 
    return -1; 
else 
{ 
    int m = (p+r)/2; 
    cout<<(a[m]==x)<<endl; 
    if(a[m]==x) 
    { 
     cout<<"entering"<<endl; 
     return (m+1); 
     cout<<"wtf?"<<endl; 
    } 
    else if(x<a[m]) 
     //Added a return statement to both the recurring function call. 
    return recursiveBinarySearch(a,p,m-1,x); 
    else if(x>a[m]) 
     //Added a return statement to both the recurring function call. 
    return recursiveBinarySearch(a,m+1, r,x); 
} 
return -2; 
} 
2

recursiveBinarySearch의 반환 값은 재귀 시도에 서면으로 무시된다 : 그것은 두 개의 재귀 호출 중 하나를 입력하면

return recursiveBinarySearch(a,p,m-1,x); 
관련 문제