title: Mergesort, using a for loop to do merge
body: <p>I am trying to write the code in C for <code>mergesort</code> using <code>for</code> loop in the merge function. Unfortunately it is not working.  In the <code>main</code> function I create an <code>array</code> on 10 <code>ints</code> in descending order and then I call the <code>mergesort</code> function to sort them. There is obviously an error in the merge function, since the ascending order is never realized and in some array sizes some long numbers intrude. What am I doing wrong? Here's the function:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  
  void mergesort(int array[], int left, int right);
  
  int main()
  {
      int i;
      int arr[10];
      for(i=10;i&gt;0;i--){
          arr[10-i]=i;
      }
      for(i=0;i&lt;10;i++){
          printf("arr[%d] = %d\n",i,arr[i]);
          }
      mergesort(arr,0,9);
      puts("\n");
      for(i=0;i&lt;10;i++){
          printf("arr[%d] = %d\n",i,arr[i]);
          }
      return 0;
  }
  
  void mergesort(int array[], int left, int right)
  {
      void merge(int array[],int left, int mid, int right);
      int mid;
      if(left&lt;right){
          mid=(left+right)/2;
          mergesort(array,left,mid);
          mergesort(array,mid+1,right);
          merge(array,left,mid,right);
      }
  }
  
  void merge(int array[], int left, int mid, int right)
  {
      int i;
      int l=0;
      int r=mid+1;
      int arr_sorted[10];
  
      for(i=0;i&lt;=right;i++){
          if((l&lt;=mid) &amp;&amp; (r&lt;=right)){
              if(array[l]&lt;array[r]){
                  arr_sorted[i]=array[l];
                  l++;
              }
              else {
                  arr_sorted[i]=array[r];
                  r++;
              }
          }
          if(l&gt;mid){
              arr_sorted[i]=array[r];
              r++;
          }
          if(r&gt;right){
              arr_sorted[i]=array[l];
              l++;
          }
      }
      for(i=0;i&lt;=right;i++){
          array[i]=arr_sorted[i];
      }
  }
  </code></pre>