2 ms·
> One interesting thing you'll notice about IEEE754 is that the values sort naturally if you interpret them as sign-magnitude integers With a few bit-twiddling
by vanderZwan 7y ago
> One interesting thing you'll notice about IEEE754 is that the values sort naturally if you interpret them as sign-magnitude integers
With a few bit-twiddling tricks you can even make them radix-sortable, as explained by Malte Skarupke:
> Michael Herf has also discovered a good way to generalize this to floating point numbers: Reinterpret cast the float to a uint32, then flip every bit if the float was negative, but flip only the sign bit if the float was positive. The same trick works for doubles and uint64s. Michael Herf explains why this works in the linked piece, but the short version of it is this: Positive floating point numbers already sort correctly if we just reinterpret cast them to a uint32. The exponent comes before the mantissa, so we would sort by the exponent first, then by the mantissa. Everything works out. Negative floating point numbers however would sort the wrong way. Flipping all the bits on them fixes that. The final remaining problem is that positive floating point numbers need to sort as bigger than negative numbers, and the easiest way to do that is to flip the sign bit since it’s the most significant bit.
Up until recently in most JS engines it was faster to sort typedarrays with a custom radix sort than with the built-in sort (seems to no longer be the case, thank goodness)
[0] https://probablydance.com/2016/12/27/i-wrote-a-faster-sorting-algorithm/ https://probablydance.com/2016/12/27/i-wrote-a-faster-sortin...
[1] http://www.codercorner.com/RadixSortRevisited.htm http://www.codercorner.com/RadixSortRevisited.htm
[2] http://stereopsis.com/radix.html http://stereopsis.com/radix.html