Re: gcc/sort

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Thu, Mar 05, 2020 at 02:22:03PM +0100, Patrick Dupre wrote:
> > After sorting the list is: 
> > 0 -5.5e-06 3 25 56 88 100 
> > -5.5e-06 2 3 25 56 88 100 
> 
> 
> #include <stdio.h>
> #include <stdlib.h>
> 
> double values[] = { 88, 56, 100, 0.0, 25, 3, -0.55e-5 };
> double values2 [] = { 88, 56, 100, 2, 25, 3, -0.55e-5 };
> 
> int dcmpfunc (const void * a, const void * b) {
> return ( *(double*)a - *(double*)b );

The comparison function is bad (at least for the possible values).
First of all, if the difference between the two doubles doesn't fit into
int, then it is undefined behavior.  That is not what you run into here
though.  The problem you run into is that the double -> int conversion
is truncating toward zero, so if there is a difference, but smaller in
absolute value than 1.0, the comparison function returns 0 as if the two
values were the same.
So at least you want something like:
double t = *(double*)a - *(double*)b;
if (t < 0) return -1;
if (t > 0) return 1;
return 0;
the rest depends on what ordering you exactly want, e.g. if you want to
order -0.0 before 0.0 or don't care, or what you want to do with NaNs/sNaNs
etc.

	Jakub
_______________________________________________
users mailing list -- users@xxxxxxxxxxxxxxxxxxxxxxx
To unsubscribe send an email to users-leave@xxxxxxxxxxxxxxxxxxxxxxx
Fedora Code of Conduct: https://docs.fedoraproject.org/en-US/project/code-of-conduct/
List Guidelines: https://fedoraproject.org/wiki/Mailing_list_guidelines
List Archives: https://lists.fedoraproject.org/archives/list/users@xxxxxxxxxxxxxxxxxxxxxxx



[Index of Archives]     [Older Fedora Users]     [Fedora Announce]     [Fedora Package Announce]     [EPEL Announce]     [EPEL Devel]     [Fedora Magazine]     [Fedora Summer Coding]     [Fedora Laptop]     [Fedora Cloud]     [Fedora Advisory Board]     [Fedora Education]     [Fedora Security]     [Fedora Scitech]     [Fedora Robotics]     [Fedora Infrastructure]     [Fedora Websites]     [Anaconda Devel]     [Fedora Devel Java]     [Fedora Desktop]     [Fedora Fonts]     [Fedora Marketing]     [Fedora Management Tools]     [Fedora Mentors]     [Fedora Package Review]     [Fedora R Devel]     [Fedora PHP Devel]     [Kickstart]     [Fedora Music]     [Fedora Packaging]     [Fedora SELinux]     [Fedora Legal]     [Fedora Kernel]     [Fedora OCaml]     [Coolkey]     [Virtualization Tools]     [ET Management Tools]     [Yum Users]     [Yosemite News]     [Gnome Users]     [KDE Users]     [Fedora Art]     [Fedora Docs]     [Fedora Sparc]     [Libvirt Users]     [Fedora ARM]

  Powered by Linux