2016-01-15 243 views
2

爲什麼程序不會在返回後終止以及如何終止? https://ideone.com/9Lz6jy 注意:這裏的目的是找到中位數是否有助於理解程序。但我的問題是純粹的C++相關。找到中位數無需任何幫助。請關注一旦我得到答案,我將如何返回答案。所有的如何使C++遞歸程序終止

#include <iostream> 
#include <time.h> 
#include <cmath> 
#include <cstdio> 
#include <vector> 
#include <iostream> 
#include <algorithm> 
#include <assert.h> 

using namespace std; 


int Pivot2(vector<int> &v, int pivot) { 

    vector<int> v_copy(v.size()); 
    //int pivot = v.size()/2; 
    //1. Sort the array about the mid term 
    int count_less = 0; 
    int j = 0; 
    for (unsigned int i = 0; i <v.size() ; i++) { 

     if (v[i]< v[pivot]) { 
      v_copy[j]=v[i]; 
      j++; 
      count_less++; 
     } 
    } 

    v_copy[j]=v[pivot]; 
    j++; 

    for (unsigned int i = 0; i <v.size(); i++) { 

     if (v[i]> v[pivot]) { 
      v_copy[j] = v[i]; 
      j++; 
     } 
    } 

    //2. if the number of less than than tmp_med increase the middle postion 
    if (count_less > v.size()/2) { 
     Pivot2(v_copy,count_less-1); 
    } 
    else if (count_less == v.size()/2) { 
     cout <<"inner " << v[pivot] <<endl ; 
     return v[pivot]; //Why the recursion does not terminate with this return? 
    } 
    else { 
     if (count_less < v.size()/2) { 
      Pivot2(v_copy, count_less + 1); 
     } 
    } 



} 


int main() { 
    // your code goes here 
    int arr[] = { 8, 7, 3, 1, 9, 4, 6, 5, 2}; 
    int n = sizeof(arr)/sizeof(arr[0]); 
    //randomize(arr, n); 
    vector<int> v(begin(arr), end(arr)); 

    int med1 = Pivot2(v,v.size()/2); 
    assert(5 == med1); 
    cout << med1 <<endl ; 
    return 0; 
} 
+1

你爲什麼不叫'Pivot2返回值( )'在'if-else if'條件下? – Atri

+1

您應該在編譯器中打開警告。如果您使用g ++,請使用-Wall。這會告訴你,你沒有從你的Pivot2函數的所有路徑返回一個值。我看到3個地方你錯過了回報。 – AaronI

+0

[遞歸函數不返回指定值]的可能重複(http://stackoverflow.com/questions/27691547/recursive-function-does-not-return-specified-value) – Barmar

回答

0

你需要從該塊中的所有條件,返回值這個版本:

if (count_less > v.size()/2) { 
    return Pivot2(v_copy,count_less-1); 
} 
else if (count_less == v.size()/2) { 
    cout <<"inner " << v[pivot] <<endl ; 
    return v[pivot]; //Why the recursion does not terminate with this return? 
} 
else { 
    if (count_less < v.size()/2) { 
     return Pivot2(v_copy, count_less + 1); 
    } 
} 
0

首先,啓用編譯器警告,你正在做的符號和無符號整數表達式之間的幾個比較。即:if (count_less > v.size()/2) {

然後,你需要返回Pivots創建

return Pivot2(v_copy,count_less - 1); 
    ^^^^^^^^ 
    ..... 
    return Pivot2(v_copy, count_less + 1); 
    ^^^^^^ 

此外,小心你的函數reaches end of non-void function。只需刪除if (count_less < v.size()/2) {,它會很好。即:

else { 
    return Pivot2(v_copy, count_less + 1); 
} 

您可以檢查Coliru