Negative zeros are equivalent to positive zeros, and yet in sorting the negatives come before positives. This behavior caused a very subtle bug in a function I wrote to compare clusters of points. I’m wondering if there is a way to disable this? Or if someone has an idea for a workaround that’s less invasive than checking every single zero entry in my 2D arrays and absing them every time I apply a rotation?
Note that Julia’s default sorting algorithm isn’t stable, so even if they were considered equal, there is no guarantee that they won’t be swapped (unless you specify a stable sorting algorithm).
You can use the lt (“less than”) argument to redefine the inequalities used for sorting. As other suggested, you also may want to use a stable sorting algorithm.
sort(x; alg=Base.Sort.DEFAULT_STABLE, lt=<).
Note that using < instead of the default isless will also change the way NaN is handled and likely cause you trouble if you have any. But, assuming a NaN-free input, should not switch -0.0 and +0.0.
EDIT:
I think I misunderstood what you were after and would rather just replace all -0.0 with +0.0.
The lt=< was what I initially was hoping for when I posted my question. That works. Thank you. And I don’t have to change any negative zeros. And using lt=< in the call to sort is just as fast (according my benchmark of my use case) as any of the other solutions that focused on replacing the negative zeros.
That’s also a nice solution to getting rid of the negative zeros.
The lt=< suggestion I made applied to scalars. For vectors, it appears that < defers to isless which uses a lexicographic order, which recursively appears to use isless on the elements. Thus, for sortslices, < is no different than the default isless. You’ll need to write your own function that determines whether a vector is less than another vector (using < for the element comparisons rather than isless), then pass that function as lt to sortslices.