Currently, I am trying to create a simple C++ Merge Sort Program.
using namespace std;
using Iterator = std::vector<int>::iterator;
using CIterator = std::vector<int>::const_iterator;
std::vector<int> merge(CIterator left_begin, CIterator left_end, CIterator right_begin, CIterator right_end) {
std::vector<int> result;
CIterator left = left_begin;
CIterator right = right_begin;
while (left != left_end && right != right_end) {
if (*left <= *right) {
result.push_back(*left);
left++;
} else {
result.push_back(*right);
right++;
}
}
while (left != left_end) {
result.push_back(*left);
left++;
}
while (right != right_end) {
result.push_back(*right);
right++;
}
return result;
}
I created a merge function that basically connects two sorted vectors into one and returns it (I am bound to use the following return type of the function merge). Then Trying to write the driver function merge sort I have the following code, that I think works correctly
void merge_sort(Iterator begin, Iterator end) {
auto difference = distance(begin, end);
if (difference <= 1) {
return;
}
Iterator middle = begin;
advance(middle, difference / 2);
merge_sort(begin, middle);
merge_sort(middle, end);
vector<int> result = merge(begin, middle, middle, end);
// But what to put here?
}
At the place of the comment mark, I don't understand what to write in order to move the sorted array a step up in the recursion. I tried
begin = result.begin();
end = result.end();
but this obviously doesnt work