简体   繁体   中英

Problem in sorting a vector using recursion

i am getting the inputed vector as the output as it is.

code:

#include <bits/stdc++.h>
using namespace std;
void insert(vector<int> v,int val){
   if(v.size()==0 || v[v.size()-1]<=val ){
     v.push_back(val);
     return;
   }
   int x = v[v.size()-1];
   v.pop_back();
   insert(v,val);
   v.push_back(x);
   return;
}
void fun(vector<int> v){
   if( v.size()==0 )
    return;
   int val = v[ v.size()-1 ];
   v.pop_back();
   fun(v);
   insert(v,val);
   return;
}
int main() {
 vector<int> v{9,4,1,-2,10,1,12,5,0,-4};
 fun(v);
 auto x= v.begin();
 for(;x!=v.end();x++)
    cout<<*x<<" ";
  }

the out put is the same input vector,ie O/p: 9,4,1,-2,10,1,12,5,0,-4 please tell where am i going wrong

You are not passing vector using a reference that's why the changes are not showing.

#include <bits/stdc++.h>
using namespace std;
void insert(vector<int> &v,int val){ // Passing vector by reference
   if(v.size()==0 || v[v.size()-1]<=val ){
     v.push_back(val);
     return;
   }
   int x = v[v.size()-1];
   v.pop_back();
   insert(v,val);
   v.push_back(x);
   return;
}
void fun(vector<int> &v){ // Passing vector by reference
   if( v.size()==0 )
    return;
   int val = v[ v.size()-1 ];
   v.pop_back();
   fun(v);
   insert(v,val);
   return;
}
int main() {
 vector<int> v{9,4,1,-2,10,1,12,5,0,-4};
 fun(v);
 auto x= v.begin();
 for(;x!=v.end();x++)
    cout<<*x<<" ";
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM