There is bitwise sorting ( radix sort ), which is used for non-negative numbers. Her idea is to sort the numbers gradually, by digits, using baskets (buckets) for each digit (from 0 to 9 ).
- We iterate over all the positions of the digits in the number (there are 10 pieces in the
Integer ). - For each position we go through all the numbers in the array and add the digit of the number corresponding to this position to the basket corresponding to this digit.
- After going through all the numbers, we "collect" the array back from the numbers stored in the baskets, in the order in which they are in the baskets.
Implementation:
private static final int RADIX = 10; public static void sort(int[] array) { List<Integer>[] buckets = new ArrayList[RADIX]; for (int i = 0; i < buckets.length; i++) { buckets[i] = new ArrayList<>(); } for (int placement = 1; placement <= 1000 * 1000 * 1000; placement *= RADIX) { for (int value : array) { int digit = (value / placement) % RADIX; buckets[digit].add(value); } int index = 0; for (List<Integer> bucket : buckets) { for (int value : bucket) { array[index++] = value; } bucket.clear(); } } }
In this case, an array of lists ( buckets ) is used as an additional structure. As part of the code optimization, you can use only those positions that are really in the sorted numbers, but this assumes the presence of a comparison, so I did not add it to the code.
There is an implementation in which as an add. structures are simply used as an array of integers ( count ):
private static final int RADIX = 10; public static int[] sort(int[] array) { for (int placement = 1; placement <= 1000 * 1000 * 1000; placement *= RADIX) { array = sortPlace(array, placement); } return array; } private static int[] sortPlace(int[] array, int placement) { int[] result = new int[array.length]; int[] count = new int[RADIX]; for (int value : array) { int digit = getDigit(value, placement); count[digit]++; } for (int i = 1; i < count.length; i++) { count[i] += count[i - 1]; } for (int i = array.length - 1; i >= 0; i--) { int digit = getDigit(array[i], placement); count[digit]--; result[count[digit]] = array[i]; } return result; } private static int getDigit(int value, int placement) { return ((value / placement) % RADIX); }
The original code can be viewed here .