简体   繁体   中英

What's wrong with my merge sort implementation (C++)?

My merger sort implementation is working only partially and even raising seg faults on occasion.

Input: 5 4 3 2 1 Output: 0 1 2 3 4

Input: 7 6 5 4 3 2 1 Output: 0 1 2 3 4 5 6

Input: 4 3 2 1 Output: [some garbage value] 1 2 3

Input: 1 2 3 4 5 67 7 8 Output: [some garbage value] 1 2 3 4 5 7 8

It seems that the odd numbered inputs aren't causing seg faults but the even numbered ones are. Still, in both cases the largest value is not appearing in the output. Any help would be appreciated.

void merge(vector<int>& a, int i, int j)
{
     int b[a.size()];
     int start = i;
     int mid = (i+j)/2;
     int k = mid+1;
     int l = i;
     while(i<=mid && k<=j)
     {
       if(a[i] >= a[k])
         b[l++] = a[k++];
       else
         b[l++] = a[i++];
     }

     if(i>mid)
     {
      while(k<=j)
        b[l++] = a[k++];
     }
     else
     {
      while(i<=mid)
        b[l++] = a[i++];
     }

     for(l=start; l<=j; l++)
       a[l] = b[l];
 }

void merge_sort(vector<int>& a, int l, int u)
{
     int m;
     if(l < u)
     {
          m = (l+u)/2;
          merge_sort(a,l,m);
          merge_sort(a,m+1,u);
          merge(a,l,u);
      }
 }

 //relevant portion in main
   cin >> n;
   cout << "n: " << n << endl;
   a.resize(n);
   for(int j=0; j<n; j++)
     cin >> a[j];

   cout << endl;
   merge_sort(a, 0, a.size());

You shouldn't go up to j (" ...<= j... ") when j could be a.size() . Try a.size() - 1 .

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