0
help! i need to make this program more time efficient
The program is to count the minimal number of swaps to neighbouring elements in an array ,untill the array is sorted in an ascending order. The time limit is 500 miliseconds. #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n,k=0; cin>>n; vector <int> v; for(int i=0;i<n;i++) { int m; cin>>m; v.push_back(m); } int i=0; // for(int i=0;i<n;i++) while(i<n) { int x=distance(v.begin(),min_element(v.begin(),v.end())); k+=x; v.erase(v.begin()+x); i++; } cout<<k; return 0; }
1 ответ
+ 2
Mihail , you should go with reserve keyword as push_back is costly without vector size being reserved...
I am not sure but what you are doing might be costlier than bubble sort and also you are playing with data by erasing it also...