I am studying C++ and I wrote the following Merge Sort algorithm. I need some comments from skilled C++ programmers to understand where it can be improved, in terms of execution time, memory usage and "style". I am aware this question is rather generic but really, any comment is appreciated, even more if well motivated.
Is it ok to return a new vector by value every time the recursive function is called?
template<typename T>
vector<T> mergeSort(vector<T> const &v, unsigned long s, unsigned long e){
if (e-s == 0) return vector<T>{}; //return empty vector
else if (e-s == 1) return vector<T>{v[s]}; //return vector with single element
else{
unsigned long mid = (e+s)/2;
vector<T> v1 = mergeSort(v, s, mid);
vector<T> v2 = mergeSort(v, mid, e);
vector<T> vr (e-s); // allocate the space needed
typename vector<T>::iterator p1 = v1.begin();
typename vector<T>::iterator p2 = v2.begin();
typename vector<T>::iterator pr = vr.begin();
while (p1 != v1.end() && p2 != v2.end()) *pr++ = (*p1 < *p2) ? *p1++ : *p2++;
while (p1 != v1.end()) *pr++ = *p1++;
while (p2 != v2.end()) *pr++ = *p2++;
return vr;
}
}
int main(int argc, const char * argv[]) {
vector<int> v {2, 7, -1, 4, 2, 6, -10};
vector<int> vsorted = mergeSort(v, 0, v.size());
return 0;
}