Search code examples
calgorithmsortingmergesort

Merge Sort Logical Error


I was actually working on assignment and found an online code on merge sort and edited it a bit, but It is giving logical error, the answer (sorted array) isn't showing up instead it shows only first 2 numbers correctly(sometimes) and I can't fix it, if you could check on my code and give me a few ideas.

#include<stdio.h>

int arr[20];       // array to be sorted

int main()
{

  int n,i;
  clrscr();
  printf("Enter the size of array\n");  // input the elements
  scanf("%d",&n);
  printf("Enter the elements:");
  for(i=0; i<n; i++)
    scanf("%d",&arr[i]);

  merge_sort(arr,0,n-1);  // sort the array

  printf("Sorted array:");  // print sorted array
  for(i=0; i<n; i++)
    printf("%d",arr[i]);
   getch();
  return 0;
}

int merge_sort(int arr[],int low,int high)
{
  int mid; int i;
  if(low<high) {

    mid=(low+high)/2;
    // Divide and Conquer
    merge_sort(arr,low,mid);
    merge_sort(arr,mid+1,high);
    // Combine


    merge(arr,low,mid,high);
  }

  return 0;
}

int merge(int arr[],int l,int m,int h)
{
  int arr1[10],arr2[10];  // Two temporary arrays to
  //hold the two arrays to be merged
  int n1,n2,i,j,k,z;

    i=0,j=0;

    for(z=l;z<=m;z++)
    {
        arr1[i]=arr[z];
        i++;
    }
    for(z=m+1;z<=h;z++)
    {
        arr2[j]=arr[z];
        j++;
    }




  n1=i;
  n2=j;
  i=0;
  j=0;
  for(k=l; k<=h; k++)
  { //process of combining two sorted arrays

    if(i<n1 && j<n2)
    {
     if(arr1[i]<=arr2[j])
     {
          arr[k]=arr1[i++];
          }
    else
         arr[k]=arr2[j++];
     }
     else if(i>=n1)
     {
      arr[k]=arr[j++];
     }
     else
     {
     arr[k]=arr[i++];
     }


  }

  return 0;
}

Solution

  • wrong part

         else if(i>=n1)
         {
          arr[k]=arr[j++];
         }
         else
         {
         arr[k]=arr[i++];
         }
    

    corrected (use arr1 and arr2 instead of arr as the source of assignments)

         else if(i>=n1)
         {
          arr[k]=arr2[j++];
         }
         else
         {
         arr[k]=arr1[i++];
         }