用Java写一个基数排序,对三位数以内的数据排序
时间: 2023-03-21 10:03:00 浏览: 67
很高兴为您解答。使用基数排序对三位数以内的数据排序的Java代码如下:
```public static void radixSort(int[] arr) {
//确定排序的趟数;
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
int time = 0;
//判断位数;
while(max > 0) {
max /= 10;
time++;
}
//建立十个队列;
List<ArrayList> queue = new ArrayList<ArrayList>();
for (int i = 0; i < 10; i++) {
ArrayList queue1 = new ArrayList();
queue.add(queue1);
}
//进行time次分配和收集;
for (int i = 0; i < time; i++) {
//分配数组元素;
for (int j = 0; j < arr.length; j++) {
//得到数字的第time+1位数;
int x = arr[j] % (int) Math.pow(10, i + 1) / (int) Math.pow(10, i);
ArrayList queue2 = queue.get(x);
queue2.add(arr[j]);
queue.set(x, queue2);
}
int count = 0;//元素计数器;
//收集队列元素;
for (int k = 0; k < 10; k++) {
while (queue.get(k).size() > 0) {
ArrayList<Integer> queue3 = queue.get(k);
arr[count] = queue3.get(0);
queue3.remove(0);
count++;
}
}
}
}
``