Search code examples
sortingmergesortdivide-and-conquer

Why is the merge printing in reverse order


So, I was learning the Merge Sort Algorithm. and I was amazed to see that the merging is printed in reverse order. You can see I am printing the merge vector v at each step but I don't understand why is it in reverse order. The final answer if perfectly fine.

void merge(vector<int> &left, vector<int> &right, vector<int> &v) {
    cout << "merged vector is : \n";
    for (auto x : v)
        cout << x << " ";
    cout << endl; 

    int l = left.size();
    int r = right.size();

    int i = 0, j = 0, k = 0;
    while (i < l && j < r) {
        if (left[i] <= right[j]) {
            v[k] = left[i];
            i++;
        } else {
            v[k] = right[j];
            j++;
        }
        k++;
    }
    while (i < l) {
        v[k++] = left[i++];
    }
    while (j < r) {
        v[k++] = right[j++];
    }
    return;
}

Solution

  • You print the destination vector v at the beginning of each step. The contents and order of the destination vector depends on how you use implement the merge sort algorithm, namely how you split the original vector, how you invoke the merge function and what is the original contents of the source vector. If you want to track the behavior of the merge sort algorithm, you should print the vector after the merge operation.

    Note also that:

    • the index variables i, j, k, l and r should have type size_t.
    • the return; statement at the end of the function is useless.