c++ - 如何使C++递归程序终止

标签 c++ recursion

为什么程序返回后不终止,如何终止? https://ideone.com/9Lz6jy 注意:此处的目的是找到有助于理解程序的中位数。但我的问题是纯 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;
}

最佳答案

您需要从此 block 返回所有条件下的值:

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

关于c++ - 如何使C++递归程序终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34821401/

相关文章:

c++ - 结构数组的数组

Java递归函数失败

postgresql - 如何在 PostgreSQL 中调试触发器递归?

java - 使用递归将 int 转换为十六进制字符串

c++ - 当构造函数上的单个参数时隐藏参数

c++ - 如何将颜色编码添加到 boost::log 控制台输出?

python - 递归函数后获取数据列表

arrays - 递归算法题(缺数)

c++ - 容器的元素如何访问其容器的 "owner"?

c++:static_cast<int> std::sqrt(x) 是否总是为平方的正整数给出准确的结果?