Search code examples
cqsort

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

Solution

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