简体   繁体   English

为什么标准库中的“ qsort”功能在我的代码中不起作用?

[英]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);
    }

Your cmp function is supposed to return 您的cmp函数应该返回

  • 1 or greater if the left value is > the right value 如果左值>右值,则为1或更大
  • 0 if the values are equal 如果值相等则为0
  • -1 or less if the left value is < the right value 如果左值<右值,则为-1或更小

Your comparison only returns 1 (for the > case) or 0 (all other cases). 您的比较仅返回1 (对于>情况)或0 (所有其他情况)。

Your cmp function is returning 1 if the left item is greater than the right item, otherwise it's returning 0 . 如果左边的项目大于右边的项目,您的cmp函数将返回1 ,否则返回0 The documentation for qsort states: 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. 

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

the cmp() function should return -1, 0 or 1 (or any negative/0/any positive)to represent ordering of the given objects. cmp()函数应返回-1、0或1(或任何负数/ 0 /任何正数)以表示给定对象的顺序。 your function returns 0 or 1. 您的函数返回0或1。

try with: 尝试:

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

From the qsort man page: 在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. 如果认为第一个参数分别小于,等于或大于第二个参数,则比较函数必须返回小于,等于或大于零的整数。 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. 在我看来,您的cmp无法做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM