问题
If have an 8-byte section of data and write a double-precision floating-point value to it, under what conditions will comparison by numerical comparison and lexicographic sorting of the bytes agree?
Current theory: positive, big-endian
I believe that if the number is positive, and the representation is big-endian, then numerical ordering of the floating-point values will match the lexicographic ordering of the bytes.
The idea is that it would first sort on the exponent, then on the mantissa. Even the "denormalized" IEEE representation shouldn't cause any problems.
Is this true?
(I'm using Node's Buffer::writeDoubleBE, but that shouldn't matter.)
Follow-up
I think a simple modification can extend this to negative numbers: XOR all positive numbers with 0x8000...
and negative numbers with 0xffff...
. This should flip the sign bit on both (so negative numbers go first), and then reverse the ordering on negative numbers. Does anyone see a problem with this?
回答1:
Your approach:
I think a simple modification can extend this to negative numbers: XOR all positive numbers with 0x8000... and negative numbers with 0xffff.... This should flip the sign bit on both (so negative numbers go first), and then reverse the ordering on negative numbers. Does anyone see a problem with this?
is definitely the answer. Moreover, it was used, for example, in dBase and clones to organize sorting on a float column, and I guess it's followed by newer DB generations.
Also, it is identical to the "total order" according to IEEE-754 for binary representations. (But not for decimal ones, the latter is much more complex.)
UPDATE: as suggested by @Sneftel: you could find replacing -0 with +0 as useful before converting to bit string.
回答2:
If you want to let Radix sorting stay a stable sorting algorithm, you have to swap all subsections of equal elemts in the negative section once more, because when you swaped the negative numbers, the original stable sorting were in stable order.
Assoc. prof. Arne Maus, Univ of Oslo
来源:https://stackoverflow.com/questions/43299299/sorting-floating-point-values-using-their-byte-representation