I am implementing radix sort using queues. As of now, it works for sorting integers, but I want to modify it to sort positive floating points as well.
public static void radixSort(int[] array) {
int max = getMaxElement(array);
List<Queue<Integer>> queues = new ArrayList<>(10);
for (int i = 0; i < 10; i++)
queues.add(new LinkedList<>());
/* insert into queues based on radix */
for (int exp = 1; max / exp > 1; exp *= 10) {
for (int value: array) {
int digit = value / exp % 10;
queues.get(digit).add(value);
}
}
/* dequeue into original array */
int index = 0;
for (int i = 0; i < 10; i++) {
while (!queue.get(i).isEmpty())
array[index++] = queues.get(i).remove();
}
}
I tried by finding the longest decimal places then multiplying each element in the array by 10 raised to the power of it so that the floating points can be sorted as integers. However, the method I used would require converting them to strings to find the . longest decimal places. Is there a more elegant way for sorting floating points?
Floating point numbers can go over a wide range (they could be very close or very far from zero) so I would not use that approach. Instead, you could sort by sign, exponent and mantissa:
You could try using the binary representation. You can convert a floating point number to its binary representation using
Double#doubleToRawLongBitsor similar.Then, you can extract the sign part, exponent and mantissa:
Observe that if the
longrepresentation of one number is greater than the other, the same holds for the corresponding floating point numbers.The sign is at the same position as it would be for
longvalues. Also, the exponent (which is more significant than the mantissa) is in the significant position. So, you could just sort thelongrepresentations instead of the actualdoubles. However, you should make sure that your sorting algorithm really works for negative numbers as well.Since you probably don't want to call
Double#doubleToLongBitsover and over, you might want to first convert your datalongs first, then sort them and finally convert them back:It shall be noted that it is very likely not efficient to use radix sort for
longvalues due to their structure. Sorting algorithms based on comparison are probably more efficient if you don't have that many numbers to sort.