java的radixsort
时间: 2023-11-12 12:56:42 浏览: 76
radix sort
3星 · 编辑精心推荐
Java的radix sort是一种非比较排序算法,它通过将数据按照位数切割成不同的数字,然后按每个位数分别比较来实现排序。以下是Java的radix sort的代码示例:
```java
public static void radixSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
int max = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
max = Math.max(max, arr[i]);
}
int maxDigit = 0;
while (max != 0) {
max /= 10;
maxDigit++;
}
int mod = 10, div = 1;
ArrayList<ArrayList<Integer>> bucketList = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < 10; i++) {
bucketList.add(new ArrayList<Integer>());
}
for (int i = 0; i < maxDigit; i++, mod *= 10, div *= 10) {
for (int j = 0; j < arr.length; j++) {
int num = (arr[j] % mod) / div;
bucketList.get(num).add(arr[j]);
}
int index = 0;
for (int j = 0; j < bucketList.size(); j++) {
for (int k = 0; k < bucketList.get(j).size(); k++) {
arr[index++] = bucketList.get(j).get(k);
}
bucketList.get(j).clear();
}
}
}
```
阅读全文