You may sort any part of an array supplying correctly a pointer to the initial element of the sorting range of elements and the number of elements in the range.
As for your problem then it is possible that its reason can be integer overflow that results in undefined behavior produced by your comparison function
int cmpfunc(const void *a, const void *b)
{
int xi = *(const int *) a;
int yi = *(const int *) b;
return (xi - yi);
}
in the return statement.
Here is a simple example. Let's xi
is equal to INT_MAX
and yi
is equal to -1
. Then the expression xi - yi
results in the integer overflow and it can be that its value will be for example a negative value while actually the function shall return a positive number because xi
is greater than yi
.
That is in any case the comparison function is wrong.
You should rewrite the comparison function the following way
int cmpfunc(const void *a, const void *b)
{
int xi = *(const int *) a;
int yi = *(const int *) b;
return ( yi < xi ) - ( xi < yi );;
}
Here is a demonstration program.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int cmpfunc(const void *a, const void *b)
{
int xi = *(const int *) a;
int yi = *(const int *) b;
return ( yi < xi ) - ( xi < yi );;
}
int main( void )
{
int a[] = { INT_MAX, INT_MAX - 1, INT_MAX - 2, -1, -2, 10, 9, 8, 7, 6 };
const size_t N = sizeof( a ) / sizeof( *a );
for ( size_t i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
size_t n = N / 2;
qsort( a, n, sizeof( int ), cmpfunc );
for ( size_t i = 0; i < n; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
qsort( a + n, N - n, sizeof( int ), cmpfunc );
for ( size_t i = n; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
for ( size_t i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
}
The program output is
2147483647 2147483646 2147483645 -1 -2 10 9 8 7 6
-2 -1 2147483645 2147483646 2147483647
6 7 8 9 10
-2 -1 2147483645 2147483646 2147483647 6 7 8 9 10
If you will try to use your comparison function with the demonstration program then at least you will get an incorrect result.
For example using an inline compiler I got the following output
2147483647 2147483646 2147483645 -1 -2 10 9 8 7 6
2147483646 2147483647 -2 -1 2147483645
6 7 8 9 10
2147483646 2147483647 -2 -1 2147483645 6 7 8 9 10
As you can see the first part of the array was sorted incorrectly.