简体   繁体   中英

wrong merge sort results

i wrote a regular merge sort array code and all i want to do is to call to this function with 'asize' and not with a number but instead of recieving [1 2 3 4 5 6 7 8 9 10] a regular sorted array i get [-858993460 1 2 3 4 5 6 7 8 9]

please help me to find the reason for this

void merge_sort(int *a,int first, int last)
{
     int middle;
            if(first < last)
           {
                middle=(first+last)/2;
                merge_sort(a,first,middle);
                merge_sort(a,middle+1,last);
                merge(a,first,middle,last);
            }
}






void main()
{

    int a[] = {9, 7, 2, 3, 5, 4, 1, 8, 6, 10};
    int asize= (sizeof a / sizeof a[0]);
  merge_sort(a, 0, asize);
For (i = 0; i < 10; i++)
        printf ("%d ", a[i]);

Because your resultant array has one strange value and one missing value, the most likely case is an off-by-one error, likely to be passing asize as the index of the last element rather than asize - 1 .

The parameters needed by your merge sort are the first and last indexes (zero-based) so, for an array of size 10, that would be 0 and 9 . You're passing 0 and 10 with your current code.

Because of this, you're actually sorting the "array":

{9, 7, 2, 3, 5, 4, 1, 8, 6, 10, ?}
 \___________________________/  |
          your array            +-- not your array

and, because ? is -858993460 (in this particular case), you end up with:

{-858993460, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
 \___________________________________/  \/ not your
              your array                 \  array

Then, printing the first ten elements gives you the output you're seeing. Unfortunately, whatever variable (or stack control information or anything really) that was holding that large negative value has now been overwritten with the value ten, not something that you really want.

What you're doing is undefined behaviour. Stop it immediately. Don't make me come over there :-)

The easy fix, by the way, is to change:

merge_sort (a, 0, asize);

into:

merge_sort (a, 0, asize - 1);

You're stepping over the end of the array into garbage. last should be asize-1 , that is, call merge_sort(a, 0, asize-1); .

merge_sort(a, 0, asize);

You should send asize-1 ie from 0 to asize-1 elements. The following is the correct one!

merge_sort(a, 0, asize-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