Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why qsort from stdlib doesnt work with double values? [C]

Tags:

c

double

qsort

I wrote a simple program to sort out my array. The problem is that the code works with int values only while I need my array to have double elements ... Any help?

#include <stdio.h>
#include <stdlib.h>

double values[] = { 88, 56, 100, 2, 25 };

int cmpfunc (const void * a, const void * b)
{
    return ( *(int*)a - *(int*)b );
}

int main()
{
    int n;

    printf("Before sorting the list is: \n");
    for( n = 0 ; n < 5; n++ )
    {
        printf("%.2f ", values[n]);
    }

    printf("\n\n");

    qsort(values, 5, sizeof(double), cmpfunc);

    printf("\nAfter sorting the list is: \n");
    for( n = 0 ; n < 5; n++ )
    {
        printf("%.2f ", values[n]);
    }

    printf("\n\n");

    return(0);
}

WORKING CODE:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double values[] = { 88, 56, 100, 2, 25 };

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

int main()
{
    int n;

    printf("Before sorting the list is: \n");
    for( n = 0 ; n < 5; n++ )
    {
        printf("%.2f ", values[n]);
    }

    printf("\n\n");

    qsort(values, 5, sizeof(double), compare);

    printf("\nAfter sorting the list is: \n");
    for( n = 0 ; n < 5; n++ )
    {
        printf("%.2f ", values[n]);
    }

    printf("\n\n");

    return(0);
}
like image 663
yak Avatar asked Dec 16 '22 03:12

yak


2 Answers

You want to sort doubles but you compare them as ints... Try this comparison function:

int cmpfunc (const void * a, const void * b)
{
  if (*(double*)a > *(double*)b)
    return 1;
  else if (*(double*)a < *(double*)b)
    return -1;
  else
    return 0;  
}
like image 168
piokuc Avatar answered Dec 30 '22 03:12

piokuc


Did you miss double* conversion ?:

Also fix as one of the comment says

int cmpfunc (const void * a, const void * b)
{
  return (*(double*)a > *(double*)b) ? 1 : (*(double*)a < *(double*)b) ? -1:0 ;
}
like image 41
P0W Avatar answered Dec 30 '22 03:12

P0W