title: MergeSort index
body: <p>I made a mergesort algorithm in java. It works, but it I don't know why. </p>
  
  <p>Here's the problem:</p>
  
  <pre><code>for(int k = 0; k &lt; r; k++)
  </code></pre>
  
  <p>If i write the for loop like that, the code will not work. However, if I change the 0 to "p-1", it will. The value of p is 1, which means that p-1 is 0. Why does p-1 work when 0 doesn't?</p>
  
  <p>Here's the rest of my code:</p>
  
  <pre><code>public class MergeSort {
  
  
  public static void main(String args[]){
      Random rand = new Random();
      int[] array = new int[10];
      for(int i = 0; i &lt;array.length; i++){
          array[i] = rand.nextInt(11);
      }
      System.out.println(Arrays.toString(array));
      mergeSort(array, 1, array.length);
      System.out.println(Arrays.toString(array));
  }
  public static void merge(int[] A, int p, int q, int r){
      //
      //length of subarray 1
      int n1 = q-p+1;
  
      //length of subarray 2
      int n2 = r-q;
  
      int[] L = new int[n1+1];
      int[] R = new int[n2+1];
  
      for(int i = 0; i &lt; n1; i++){
          L[i] = A[p+i-1];
      }
  
      for(int j=0; j&lt; n2; j++){
          R[j] = A[q+j];
      }
  
      L[n1] = Integer.MAX_VALUE;
      R[n2] = Integer.MAX_VALUE;
  
      int i = 0;
      int j = 0;
  
      for(int k = p-1; k &lt; r; k++){
          if(L[i] &lt;= R[j]){
              A[k] = L[i];
              i++;
          }
          else{
                  A[k] = R[j];
                  j++;
              }
      }
  
  
  }
  
  public static void mergeSort(int[] A, int p, int r){
      if (p&lt;r){
          int q = (int) Math.floor((r+p)/2);
          mergeSort(A, p, q);
          mergeSort(A, q+1, r);
          merge(A, p, q, r);
      }
  }
  </code></pre>