Re: qsort() results: implementation dependent?



On Wed, 28 Jun 2006 00:13:47 -0700, Max wrote:

Hi everybody,

suppose you have to order a list of integers which refer to points
located in the 3D space. The compare() function is based on the
distance that these points have with respect to the origin (0,0,0). So,
using the standart qsort() function, I think this task should be
accomplished as follows:

qsort(int_vector, (size_t)no_of_points, sizeof(int), compare_function);

where

static int compare_function(void *b0, const void *b1)
{
double eps = 1e-6;

int pnt0 = *((int *)b0);
int pnt1 = *((int *)b1);

double d0 = get_distance(pnt0);
double d1 = get_distance(pnt1);

double dd = d0 - d1;

if(dd > eps)
return 1;
else if (dd < -eps)
return -1;
else
return 0.;

}

The question is: why two different qsort() implementations (AIX and
Linux) should give different results? In particular, the Linux
implementation seems to fail to to find the right order. Any hint?
Thanks
Max
I'm not sure if this is specified for qsort but I've learnt not to use
it unless the compare function really is an order, ie unless the compare
function only returns 0 if the two arguments are identical. Otherwise, in
may experience at least, qsort can fail spectacularly (cause a core dump),
and anyway I'd suspect that if it returns the final order of the array,
(ie the order of the elements that are all equal as fare as the compare is
concerned) is not just implementation but phase-of-the-moon dependent if
the compare can return non zero for two different arguments
Could you perhaps extend your comparison, function, eg if two points
are the same distance from the origin, compare x then y
then z coordinates too?
Duncan

.



Relevant Pages