title: Merge Sort based on CLRS textbook
body: <p>The following code is in accordance with the CLRS (<a href="https://rads.stackoverflow.com/amzn/click/com/0262033844" rel="nofollow noreferrer" rel="nofollow noreferrer">Corman, Leiserson, Rivest, Stein — 'Introduction to Algorithms'</a>) textbook which is supposed to do merge sorting.</p>
  
  <p>I am unable to identify the mistake that is happening, although I know there is something wrong happening in the <code>mergesort()</code> function. I think <code>merge()</code> is functionally intact.</p>
  
  <pre><code>/* Merge sort as per CLRS */
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  void merge(int *a,int p,int q,int r){
  int n1 = q - p + 1;
  int n2 = r - q;
  int* l = malloc((n1+1)*sizeof(int));
  int* ri = malloc((n2+1)*sizeof(int));
  int i,j;
  for(i = 0 ; i &lt; n1 ; i++)
      l[i] = a[p+i-1];
  for(i = 0 ; i &lt; n2 ; i++)
      ri[i] = a[q+i];
  l[n1] = 9999;
  ri[n2] = 9999;
  i = 0;
  j = 0;
  int k;
  for ( k = p ; k &lt;= r ; k++){
      if( l[i] &lt; ri[j] ){
          a[k] = l[i];
          i++;
      }
      else{
          a[k] = ri[j];
          j++;
      } 
  }
  }
  
  void mergeSort(int* a,int p,int r){
  if( p &lt; r){
  
      int q = ( p + r ) / 2;
      mergeSort(a,p,q);
      mergeSort(a,p+1,r);
      merge(a,p,q,r);
  }
  
  else return;
  
  }
  
  int main(int argc, char* argv[]){
  int a[] = {9,21,4,15,1,3};
  
  mergeSort(a,0,5);
  
  int i;
  for( i = 0 ; i &lt; 6 ; i++){
      printf("%d ",a[i]);
  }
  return 0;
  
  }
  </code></pre>