title: Merge sort in C++ - strange behavior of a program
body: <p>Update: modified condition in the merge function, now everything works fine</p>
  
  <p>I'm trying to implement a merge sort algorithm in c++ which works with intege vectors. So here is my piece of code:</p>
  
  <pre><code>#include &lt;vector&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  void Vout (vector &lt;int&gt; V){
      for (int i = 0; i&lt;V.size(); i++)
          cout &lt;&lt; V[i] &lt;&lt; "\t";
      cout &lt;&lt; endl;
  }
  
  vector &lt;int&gt; merge (vector &lt;int&gt; B, vector &lt;int&gt; C){
      vector &lt;int&gt; D;
      int n = B.size() + C.size();
      int i=0, j=0;
  
      for (int k = 0; k&lt;n; k++){
          if( ( B[i]&lt;C[j] || j == C.size() ) &amp;&amp; i&lt;B.size() ){  //was like this: if( B[i]&lt;C[j] ){
              D.push_back(B[i]);
              i++;
          }
          else{
              D.push_back(C[j]);
              j++;
          }
      }
      return D;
  }
  
  vector &lt;int&gt; merge_sort(vector &lt;int&gt; A){
      int n = A.size();
      if (n&lt;=1) return A;
      vector &lt;int&gt; B, C;
      for (int i = 0; i&lt;n/2; i++)
          B.push_back(A[i]);
      for (int i = n/2; i&lt;n; i++)
          C.push_back(A[i]);
  
      B = merge_sort(B);
      C = merge_sort(C);
      vector &lt;int&gt; D = merge(B, C);
      return D;
  }
  
  
  int main() {
      vector &lt;int&gt; data;
      freopen("input.txt", "rt", stdin);
      int n;
      while (cin &gt;&gt; n){
          data.push_back(n);}
      Vout (data);
      Vout (merge_sort(data));
  }
  </code></pre>
  
  <p>However with this input</p>
  
  <blockquote>
    <p>5 4   6   7   9   1   2   8   3   12  10</p>
  </blockquote>
  
  <p>it gives the following output:</p>
  
  <blockquote>
    <p>1 2   3   0   4   5   6   7   8   9   0</p>
  </blockquote>
  
  <p>I don't quite understand where all these zeroes came from. Please help.</p>