tags:

views:

80

answers:

4
#include<stdio.h>
#include<stdlib.h>
#define MAX 1000
struct island{  double left;           //gobal
                double right;
                } island[MAX];
...

int cmp(const void *ptr1,const void *ptr2 )           
{
    return (*(struct island*)ptr1).right >  (*(struct island*)ptr2).right;
}

qsort(island,num,sizeof(island[0]),cmp);    // "num" is the number of the input data

 //when I do print,it seems that if num<10 is right,else wrong
for(i=0;i<num;i++)          
    {
        printf("%g\t",island[i].right);
    }
A: 

the cmp() function should return -1, 0 or 1 (or any negative/0/any positive)to represent ordering of the given objects. your function returns 0 or 1.

try with:

int cmp(const void *ptr1,const void *ptr2 )           
{
    return (*(struct island*)ptr2).right - (*(struct island*)ptr1).right;
}
Javier
I believe this will be problematic when the difference between the double values exceeds the maximum value of an int (which is very likely given the range of doubles.
Matt Joiner
"Comparison by subtraction" is always a bug, except for a few rare cases.
AndreyT
This will always return zero. Can you see why? :-)
Platinum Azure
@Matt, Andrey: right, this is just a sample to show the intent. maybe `strcmp()` would be a better example.
Javier
@Platinum Azure: thx, fixed
Javier
+1  A: 

Your cmp function is returning 1 if the left item is greater than the right item, otherwise it's returning 0. The documentation for qsort states:

 The comparison function must return an integer less than, equal to,  or
   greater  than  zero  if  the first argument is considered to be respec‐
   tively less than, equal to, or greater than the second. 

Try this for your compare function:

int cmp(const void *ptr1, const void *ptr2)           
{
    double first = (*(struct island *)ptr1).right;
    double second = (*(struct island *)ptr2).right;
    if (first < second) return -1;
    else if (first > second) return 1;
    else return 0;
}
Matt Joiner
+2  A: 

Your cmp function is supposed to return

  • 1 or greater if the left value is > the right value
  • 0 if the values are equal
  • -1 or less if the left value is < the right value

Your comparison only returns 1 (for the > case) or 0 (all other cases).

Nate
A: 

From the qsort man page:

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respec‐ tively less than, equal to, or greater than the second. If two members compare as equal, their order in the sorted array is undefined.

It looks to me like your cmp doesn't do that.

Nathon