How to make the C++ recursion program terminate -


why program not terminate after return , how make terminate ? https://ideone.com/9lz6jy note: intent here find median if helps in understanding program. question pure c++ related. no needed in finding median. please focus on how can return answer once have fount it.

#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 array mid term       int count_less = 0;      int j = 0;      (unsigned int = 0; <v.size() ; i++) {          if (v[i]< v[pivot]) {             v_copy[j]=v[i];              j++;              count_less++;          }     }      v_copy[j]=v[pivot];     j++;       (unsigned int = 0; <v.size(); i++) {          if (v[i]> v[pivot]) {             v_copy[j] = v[i];             j++;          }     }      //2.  if number of less  tmp_med increase 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 recursion not terminate return?     }     else {         if ( count_less < v.size() / 2) {             pivot2(v_copy, count_less + 1 );         }     }    }   int main() {     // 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; } 

you need return values in condition 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 recursion not terminate return? } else {     if ( count_less < v.size() / 2) {         return pivot2(v_copy, count_less + 1 );     } } 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

android - Keyboard hides my half of edit-text and button below it even in scroll view -