开发者

Why doesn't function "qsort" in the standard library work in my code?

#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(开发者_StackOverflow中文版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);
    }


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).


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;
}


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.


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜