Radix sort for floating-point numbers by transforming their bit representation to preserve numeric order.
Floating point radix sort sorts floating point numbers by transforming their binary representation into an order-preserving integer form, then applying standard radix sort.
The main challenge is that IEEE floating point bit ordering does not match numeric ordering for negative values.
Problem
Given an array of floating point numbers (typically IEEE 754), sort the array in increasing order.
Idea
Each floating point number is represented as:
- sign bit
- exponent
- mantissa
Direct bitwise comparison fails because:
- negative numbers have sign bit 1
- bitwise order places all negative numbers after positive numbers
To fix this, transform each number into a sortable integer key.
Transformation
Let be a floating point value interpreted as an unsigned integer bit pattern.
Define transformed key:
where:
- sign_mask flips the sign bit
- is bitwise complement
This ensures:
- negative values map to smaller keys
- ordering matches numeric comparison
Algorithm
float_radix_sort(A):
convert each float to integer bits
for each element:
if sign bit is 0:
key = bits XOR sign_mask
else:
key = bitwise NOT bits
radix sort keys
reverse transformation to recover floats
return sorted arrayExample
Consider:
After transformation:
- negative numbers map to low integer range
- positive numbers map to high range
After radix sorting and inverse mapping:
Correctness
The transformation maps floating point values to integers such that:
Thus sorting transformed keys yields the correct numeric order. Since radix sort preserves integer ordering exactly, the final result is sorted.
Complexity
Let:
- be number of elements
- be number of bytes per float (typically 4 or 8)
Time:
Space:
Properties
| property | value |
|---|---|
| stable | yes, if radix sort is stable |
| in place | no |
| comparison based | no |
| handles floats | yes |
When to Use
Use floating point radix sort when:
- sorting large arrays of floats
- performance is critical
- radix sort is already implemented
Avoid when:
- small arrays
- simplicity is preferred
- non-IEEE formats are used
Implementation (Python)
import struct
def float_radix_sort(a):
def float_to_int(x):
bits = struct.unpack('>Q', struct.pack('>d', x))[0]
if (bits >> 63) == 0:
return bits ^ (1 << 63)
else:
return ~bits & ((1 << 64) - 1)
def int_to_float(x):
if (x >> 63) == 1:
bits = x ^ (1 << 63)
else:
bits = ~x & ((1 << 64) - 1)
return struct.unpack('>d', struct.pack('>Q', bits))[0]
keys = [float_to_int(x) for x in a]
keys = sorted(keys) # replace with radix sort if needed
return [int_to_float(k) for k in keys]