title: Implementing merge sort in java
body: <p>Here's my implementation of Merge Sort in java</p>
  
  <pre><code>import java.io.*;
  import java.util.Arrays;
  
  public class MergeSort
  {
    private static int [] LeftSubArray(int [] Array)
    {
      int [] leftHalf = Arrays.copyOfRange(Array, 0, Array.length / 2);
      return leftHalf;
    }
  
    private static int [] RightSubArray(int [] Array)
    {
      int [] rightHalf = Arrays.copyOfRange(Array, Array.length / 2 + 1, Array.length);
      return rightHalf;
    }
  
    private static int [] Sort(int [] A)
    {
      if(A.length &gt; 1)
      {
        return Merge( Sort( LeftSubArray(A) ) , Sort( RightSubArray(A) ) );
      }
      else
      {
        return A;
      }
    }
  
    private static int [] Merge(int [] B, int [] C)
    {
      int [] D = new int[B.length + C.length];
      int i,j,k;
      i = j = k = 0;
      while(k &lt; D.length)
      {
        if(i == B.length)
        {
          //Copy the remainder of C into D
          while(k &lt; D.length){ D[k++] = C[j++]; }
        }
        if(j == C.length)
        {
          //Copy the remainder of B into D
          while(k &lt; D.length){ D[k++] = B[i++]; }
        }
        if(i&lt;B.length &amp;&amp; j&lt;C.length)
        {
          if(B[i] &gt; C[j]){ D[k++] = B[i++]; }
          else { D[k++] = C[j++]; }
        }
      }
      return D;
    }
  
    public static void main(String [] args)
    {
      int [] array = {1,3,5,2,4};
      int [] sorted = MergeSort.Sort(array);
      for(int i = 0;i &lt; sorted.length; ++i)
      {
        System.out.print(sorted[i] + " ");
      }
    }
  }
  </code></pre>
  
  <p>The output I get is</p>
  
  <pre><code>2 1
  </code></pre>
  
  <p>From what I can tell there seems a problem with my division of the right sub array.
  What am I doing wrong?</p>