I have read and understood how Mergesort works (as a text) and now I'm trying to code it. I have finished the part where you divide the data (I use vectors) until it has each size of 1. Now I have written code for another required part in Mergesort, I don't know how to call it but I just call it "compare and ordering part".
You have 2 vectors and this part is supposed to compare the very first elements, take the smaller element, then remove the chosen element and put it inside a new vector. Doing that untill both vectors have size 0.
I'm sorry for the long code but I really don't see why the very last element is ignored by the code? : / I have added some comments so maybe it is easier to follow what I tried to do.
I tried as input:
vector<int> v1 = {1,4,5,9}; vector<int> v2 = {2,3,6,7,8};
Output:
1 2 3 4 5 6 7 8 0
vector<int> sortit(vector<int> &left, vector<int> &right) {
vector<int> sorted(left.size() + right.size());
int i = 0;
while (left.size() > 0 && right.size() > 0) {
if (left.at(0) <= right.at(0)) {
sorted.at(i) = left.at(0); // putting the smaller element into the new vector
left.erase(left.begin()); // removing this smaller element from the (old) vector
}
else if (right.at(0) <= left.at(0)) {
sorted.at(i) = right.at(0); // see comment above
right.erase(right.begin()); // see comment above
}
else if (left.size() <= 0 && right.size() > 0) { // if left vector has no elements, then take all elements of the right vector and put them into the new vector
while (right.size() > 0) {
sorted.at(i) = right.at(0);
right.erase(right.begin());
}
}
else if (right.size() <= 0 && left.size() > 0) { // the same just for the right vector
while (left.size() > 0) {
sorted.at(i) = left.at(0);
left.erase(left.begin());
}
}
i++;
}
return sorted;
}