I'm trying to implement mergesort in cpp, I'm having some trouble with the proper syntax with vectors, in particular the part inside the for loop where I'm merging the elements. Some help would be appreciated. My code so far gives the wrong output. Also, I was wondering if this code could be modified to count inversions as well, everytime I go in the else case, inversions increase but it's missing corner cases. I tried doing the v[i] = left[i1]
as v.insert(v.begin() + i, left.at(i1))
, which also did not work, I'm in general confused about the []
operator for vectors, how is it different than array []
operator?
#include <bits/stdc++.h>
using namespace std;
void mergeSort(vector<int>& v) {
if(v.size() > 1) {
vector<int> left(v.begin(), v.begin() + v.size()/2);
vector<int> right(v.begin() + v.size()/2, v.end());
mergeSort(left);
mergeSort(right);
int i1 = 0;
int i2 = 0;
for(int i = 0; i < v.size(); i++) {
if(i2 >= right.size() || (i1 < left.size() && left[i] < right[i])) {
v[i] = left[i1]; i1++;
} else {
v[i] = right[i2]; i2++;
}
}
}
}
int main() {
vector<int> v = {22, 18, 12, -4, 58, 7, 31, 42};
mergeSort(v);
for(auto i = v.begin(); i != v.end(); i++) cout << *i << endl;
return 0;
}