[英]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(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);
}
您的cmp
函数应该返回
>
右值,则为1
或更大 0
<
右值,则为-1
或更小 您的比较仅返回1
(对于>
情况)或0
(所有其他情况)。
如果左边的项目大于右边的项目,您的cmp
函数将返回1
,否则返回0
。 qsort
的文档指出:
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.
尝试使用此作为比较功能:
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;
}
cmp()
函数应返回-1、0或1(或任何负数/ 0 /任何正数)以表示给定对象的顺序。 您的函数返回0或1。
尝试:
int cmp(const void *ptr1,const void *ptr2 )
{
return (*(struct island*)ptr2).right - (*(struct island*)ptr1).right;
}
在qsort手册页中:
如果认为第一个参数分别小于,等于或大于第二个参数,则比较函数必须返回小于,等于或大于零的整数。 如果两个成员比较相等,则它们在排序数组中的顺序是不确定的。
在我看来,您的cmp无法做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.