简体   繁体   中英

Merge Sort code in C not working properly

So i have written a C code for merge sort which works for an array of 3 elements but is giving garbage value when i increase the number of elements. Since, this sis a recursive code this type of problem should not arise. What am i doing wrong? This gave an output of something like:2,5,1881172767,32718, I don't understand the origin of these garbage values.

#include<stdio.h>

 void merge(int *a,int s,int m,int e)
 {
  int l1,l2;
  int c[50];
  l1=m-s+1;
  l2=e-m;
  int i=0,i1=0,i2=0;
  while(i1<l1 && i2<l2)
  {
    if(a[i1]<a[i2+m+1])
     {
      c[i]=a[i1];
      i1++;
     }
    else
     {
      c[i]=a[i2+m+1];
      i2++;
     }
     i++;
  }

   while(i1<l1)
   {
    c[i]=a[i1];
    i1++;
    i++;
   }
  while(i2<l2)
  {
   c[i]=a[i2+m+1];
   i2++;
   i++;
  }

  for(i=0;i<=e;i++)
   {
    a[i]=c[i];
   }
 }


 void mergesort(int *a,int s,int e)
 {
  int m;
  if(s<e)
  {
   m=(s+e)/2;
   mergesort(a,s,m);
   mergesort(a,m+1,e);
   merge(a,s,m,e);
  }
 }

 void main()
 {
  int i;
  int a[4]={3,2,1,5};
  mergesort(a,0,3);

  for(i=0;i<4;i++)
    printf("%d,",a[i]);
 }

You forgot to add an offset of s when addressing elements in a or c. As long as s == 0, there is no problem. But when your array becomes larger, you copy elements only into the first part of your array, and the last elements keep uninitialised.

Your code

if(a[i1]<a[i2+m+1])
  {
    c[i]=a[i1];
    i1++;
  }

v.gr should be

if(a[i1+s]<a[i2+m+1])
  {
    c[i+s]=a[i1+s];
    i1++;
  }

Correct this also further in your code.

Normally, for that kind of operations, C prefers to use pointers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM