Update: modified condition in the merge function, now everything works fine
I’m trying to implement a merge sort algorithm in c++ which works with intege vectors. So here is my piece of code:
#include <vector>
#include <iostream>
using namespace std;
void Vout (vector <int> V){
for (int i = 0; i<V.size(); i++)
cout << V[i] << "\t";
cout << endl;
}
vector <int> merge (vector <int> B, vector <int> C){
vector <int> D;
int n = B.size() + C.size();
int i=0, j=0;
for (int k = 0; k<n; k++){
if( ( B[i]<C[j] || j == C.size() ) && i<B.size() ){ //was like this: if( B[i]<C[j] ){
D.push_back(B[i]);
i++;
}
else{
D.push_back(C[j]);
j++;
}
}
return D;
}
vector <int> merge_sort(vector <int> A){
int n = A.size();
if (n<=1) return A;
vector <int> B, C;
for (int i = 0; i<n/2; i++)
B.push_back(A[i]);
for (int i = n/2; i<n; i++)
C.push_back(A[i]);
B = merge_sort(B);
C = merge_sort(C);
vector <int> D = merge(B, C);
return D;
}
int main() {
vector <int> data;
freopen("input.txt", "rt", stdin);
int n;
while (cin >> n){
data.push_back(n);}
Vout (data);
Vout (merge_sort(data));
}
However with this input
5 4 6 7 9 1 2 8 3 12 10
it gives the following output:
1 2 3 0 4 5 6 7 8 9 0
I don’t quite understand where all these zeroes came from. Please help.
Your
merge()function doesn’t handle running off the end of theBorCvectors; when it reaches the end of either, your comparison (B[i]<C[j]) will be comparing against one past the end of the array.