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
asizeas the index of the last element rather thanasize - 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
0and9. You’re passing0and10with your current code.Because of this, you’re actually sorting the “array”:
and, because
?is-858993460(in this particular case), you end up with: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:
into: