2

I'm new to using qsort, and I'm attempting to qsort a predefined array of doubles, unfortunately the result I receive is all 0's after the array has been sorted using qsort. I'm completely lost, and any advice would be greatly appreciated. Here is the code I am using to sort this array of doubles.

static int compare (const void * a, const void * b){
    if (*(const double*)a > *(const double*)b) return 1;
    else if (*(const double*)a < *(const double*)b) return -1;
    else return 0;  
}

double stuff[] = {255, 1, 5, 39.0};
qsort(stuff, 4, sizeof(double), compare);
int i;
for(i = 0; i < 4; i++){
    printf("%d %s", stuff[i], " ");
}
Man Person
  • 1,122
  • 8
  • 20
  • 34

2 Answers2

2

Your problem is the way you are printing the result with your printf() function. To print double values, you need to use %f, like this:

printf("%f ", stuff[i]);

Also, just a sidenote: you don't need these else statements in your compare function, since once the condition is evaluated as true, it will return the function.

Natan Streppel
  • 5,759
  • 6
  • 35
  • 43
  • Hah, what a simple mistake. Thanks for the help, and yes I do know that the compare function is slightly inefficient, honestly I copied and pasted it just to test out if qsort will work in the first place. – Man Person Sep 20 '13 at 01:52
  • Those simple mistakes can turn out to be the toughest ones to find out sometimes :-) – Natan Streppel Sep 20 '13 at 01:53
  • Why `%lf` since there is no `long double`? `%f` should be enough here. – bkausbk Sep 20 '13 at 04:48
1

As already noted, the problem is in the format specifier you used with printf(): %d (which you used) is not good for doubles; you should use something like %f or %g instead. See this Q&A on StackOverflow for more details.

Something like:

printf("%g ", stuff[i]);

should be just fine.

(Note that you don't need to pass "%s" and single-space string literal to printf() either.)

Moreover, I'd like to show you how to better write your compare() function:

  1. You can assign the raw void* pointers to some constant value at the beginning of function body, to avoid repeating the (ugly) casts, and making the code clearer and more readable.

  2. You may want to simplify your if...else if...else structure, and just use a simpler if...return structure.

Something like this:

static int compare(const void * a, const void * b) 
{
    const double lhs = *(const double *)a;
    const double rhs = *(const double *)b;

    if (lhs > rhs)
        return 1;

    if (lhs < rhs)
        return -1;

    return 0;
}
Community
  • 1
  • 1
Mr.C64
  • 41,637
  • 14
  • 86
  • 162