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

时间:2010-10-13 14:06:01

标签: c qsort

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

4 个答案:

答案 0 :(得分:2)

你的cmp函数应该返回

    如果左侧值为1正确值,则为
  • >或更高 如果值相等,则
  • 0
  • 如果左侧值为-1正确值,则为
  • <或更少

您的比较仅返回1(针对>案例)或0(所有其他案例)。

答案 1 :(得分:1)

如果左侧项目大于正确的项目,则cmp函数返回1,否则返回0qsort州的文档:

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

答案 2 :(得分: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;
}

答案 3 :(得分:0)

来自qsort手册页:

比较函数必须返回小于,等于或的整数 如果第一个参数被认为是re​​spec-大于零 小于,等于或大于第二个。如果是两个成员 比较相等,它们在排序数组中的顺序是未定义的。

在我看来,你的cmp不会这样做。