Running merge sort and printing the left part gives me the following output for given input, I am not able to understand why it is printing 2
at the end. Please help me with how this recursive calls are
Input: (size of array and in the next line is the array)
5
8 5 4 2 1
and the output is
8
5 8
4 5 8
2
1 2 4 5 8
here is my full code for reference, it is very standard algorithm so just check mergesort
function and see what I am trying to print.
#include <bits/stdc++.h>
using namespace std;
vector<int> merge(vector<int>&B, vector<int>&C) {
int n = B.size() + C.size();
vector<int> D(n);
for (int t{}; t < n; t++)
D[t] = 0;
int i{}, j{}, k{};
while (i < B.size() && j < C.size()) {
if (B[i] < C[j]) {
D[k] = B[i];
i++;
k++;
} else {
D[k] = C[j];
j++;
k++;
}
}
if (i < B.size()) {
while (i < B.size()) {
D[k] = B[i];
k++;
i++;
}
} else {
while (j < C.size()) {
D[k] = C[j];
k++;
j++;
}
}
return D;
}
vector<int> merge_sort(vector<int> &A, int left, int right) {
vector <int> B, C, A_;
if (left == right) {
A_.push_back(A[left]);
return A_;
}
int m = (left + right) / 2; //possible error, convert this to int then
B = merge_sort(A, left, m);
for (int i{}; i < B.size(); i++)
cout << B[i] << " ";
cout << endl;
C = merge_sort(A, m + 1, right);
A_ = merge(B, C);
return A_;
}
int main() {
int n;
cin >> n;
vector<int> vec(n);
for (int i{}; i < n; i++)
cin >> vec[i];
vector<int> sorted_vec = merge_sort(vec, 0, vec.size() - 1);
for (int i{}; i < n; i++)
cout << sorted_vec[i] << " ";
cout << endl;
return 0;
}
That's because you call cout only on the left side of the vector (for each recursion call) in a depth first visit: you always print what happens on the left and only for the left nodes (and after the left side has been sorted). This drawing should help you understanding:
85421 represents your first call to merge_sort. There you have vector B (854) and vector C (21)
you print B vector (458)
you call merge sort on (21) vector B is (2) and vector C is (1)
you merge (458) and (12) and (12458) is the result.
you print (12458) in the main
Hope this was helpful:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.