2016-01-15 215 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