title: Java mergesort algorithm
body: <pre><code>public class mergesort {
  public static int[] mergesort (int[] input) {
      int length = input.length;
      if (length &lt;= 1) {
          return input;
      }
      int median = length/2;
      int[] left = new int[median];
      int[] right = new int[length-median];
      for (int x = 0; x&lt; median; x++) {
          left[x] = input[x];
      }
      for (int y = median; y &lt; length; y++) {
          right[y-median] = input[y];
      }
      mergesort(left);
      mergesort(right);
      merge(left, right, input);
      return input;
  }
  public static int[] merge (int[] left, int[] right, int[] input) {
      int a = 0;
      int b = 0;
      int c = 0;
      int leftlength = left.length;
      int rightlength = right.length;
      while (a&lt;leftlength &amp;&amp; b&lt;rightlength) {
          if (left[a] &lt; right[b]) {
              input[c] = left[a];
              a++;
          } else {
              input[c] = right[b];
              b++;
          }
          c++;
      }
      return input;
  }
  
  public static void main(String[] args) {
      int[] inputArr = {45,23,11,89,77,98,4,28,65,43};
      mergesort mms = new mergesort();
      inputArr = mms.mergesort(inputArr);
      for(int i = 0; i &lt; inputArr.length; i ++){
          System.out.print(inputArr[i]);
          System.out.print(" ");
      }
  }
  </code></pre>
  
  <p>This above is my attempt at the merge-sort algorithm. The last code block with <code>main(String[] args)</code> is a test run to see if my algorithm works. </p>
  
  <p>The code still prints out an array (before, it just threw off an error).
  However, while the algorithm should be printing </p>
  
  <pre><code>4, 11, 23, 28, 43, 45, 65, 77, 89,and 98, 
  </code></pre>
  
  <p>the code prints:</p>
  
  <pre><code>4 4 11 23 23 28 65 43 65 43, 
  </code></pre>
  
  <p>which is obviously not the intended result.</p>
  
  <p>How can I fix my code?</p>
  
  <p>It's my first post here, so please let me know if I'm not allowed to post these kinds of material, etc.</p>
  
  <p>Edit: This is (surprisingly) an edited version of the original code. Before, the code threw off an error, but now at least it prints something. Manipulating small parts of the code (ex. changing median to median+1, etc) didn't work out, and I didn't think it would be very significant to post a plethora of trial-and-failure results that may be deemed insignificant to some.</p>
  
  <p>And yes, I honestly didn't know where to go from here. I asked my friend to review the code, and he used the debugger to check the code, but there weren't any meaningful discoveries, thus this post.</p>