Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting wrong output while sorting in C++

Tags:

c++

sorting

qsort

The following C++ code sorts an array in descending order using qsort:

#include<iostream>
#include<cstdio>
#include <stdlib.h>
using namespace std;

struct player {
  double data;
  int index;
};

struct player A[] = {{0.690277,0}, {0.517857,1}, {0.780762,2}, {0.0416667,3}, {0.0416667,4}};

int compare (const void * a, const void * b)
{
   return ( ((struct player*)b)->data - ((struct player*)a)->data );
}

int main ()
{
  int n;
  qsort (A, 5, sizeof(struct player), compare);
  for (n=0; n<5; n++)
  printf ("data=%lf, index=%d\n", A[n].data, A[n].index);
  return 0;
}

But I am getting output like this:

data=0.517857, index=1
data=0.780762, index=2
data=0.041667, index=3
data=0.041667, index=4
data=0.690277, index=0

Is there anything wrong in the code?

like image 589
user5411115 Avatar asked Aug 30 '26 23:08

user5411115


1 Answers

In compare, you are subtracting two sub-1 doubles and casting them to an int, the result will in most cases be 0. Instead of subtracting you should compare them and return -1/1.

like image 79
weltensturm Avatar answered Sep 01 '26 18:09

weltensturm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!