/**
* @Description 基数排序
* 就是先将对应的数据的从最低位的数据往最高位排序
* 依次将对应的数据放到对应的容器中
* @auther Eleven
* @create 2020-04-05 15:22
**/
public class RadixSort {
public static void main(String[] args) {
// int[] arr = {100,12,133,-176,-49,-5,892,925,-4,-1527};
int[] arr = {100,12,133,176,49,5,892,925,4,-1527};
radixSort(arr);
}
public static void radixSort(int[] arr){
//定义一个二维数组作为存储每个轮次的容器
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//-9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9
int[][] container = new int[19][arr.length];
//定义数组存储每个容器中有多少个数据
int[] counts = new int[19];
//首先获取当前数组的最大值
int maxVal = 0;
for (int i=0;i<arr.length;i++){
int temp;
if (arr[i]<0){//负数换成正数比较
temp = arr[i]*-1;
}else{
temp = arr[i];
}
if (temp>maxVal){
maxVal=temp;
}
}
//打印绝对值最大的值
System.out.println("当前数据绝对值最大的值:"+maxVal);
//算出绝对值最大的值的数据级别就是位数
int maxLength = (maxVal+"").length();
System.out.println(maxLength);
//循环maxLength的轮次,取出所有的个、十、百等等位的值
for (int i = 0,n=1;i<maxLength;i++,n=n*10){
for (int j=0;j<arr.length;j++){
int ys = arr[j]/n%10+9;
container[ys][counts[ys]] = arr[j];
counts[ys]++;
}
//用于输出第一轮的结果
/* if (i==1){
System.out.println(Arrays.toString(counts));
for (int[] temp:container){
System.out.println(Arrays.toString(temp));
}
}*/
//再将数字取出来
int index = 0;
for (int k= 0;k<counts.length;k++){
if (counts[k]>0){
for (int l = 0;l<counts[k];l++ ){
arr[index] = container[k][l];
index++;
}
counts[k]=0;
}
}
}
System.out.println(Arrays.toString(arr));
}
/**
* 用队列实现
* @param arr
*/
public static void radixSort4Queue(int[] arr){
//首先获取当前数组的最大值
int maxVal = 0;
for (int i=0;i<arr.length;i++){
int temp;
if (arr[i]<0){//负数换成正数比较
temp = arr[i]*-1;
}else{
temp = arr[i];
}
if (temp>maxVal){
maxVal=temp;
}
}
//打印绝对值最大的值
System.out.println("当前数据绝对值最大的值:"+maxVal);
//算出绝对值最大的值的数据级别就是位数
int maxLength = (maxVal+"").length();
System.out.println(maxLength);
Queue[] myQueue = new Queue[19];
for (int i=0;i<myQueue.length;i++){
myQueue[i] = new ConcurrentLinkedDeque();
}
//循环maxLength的轮次,取出所有的个、十、百等等位的值
for (int i = 0,n=1;i<maxLength;i++,n=n*10){
for (int j=0;j<arr.length;j++){
int ys = arr[j]/n%10+9;
myQueue[ys].add(arr[j]);
}
//再将数字取出来
int index = 0;
for (int k= 0;k<myQueue.length;k++){
while (!myQueue[k].isEmpty()){
arr[index] = (int) myQueue[k].poll();
index++;
}
}
}
System.out.println(Arrays.toString(arr));
}
}
基数排序
最新推荐文章于 2025-03-03 19:59:24 发布
本文深入解析基数排序算法,介绍其工作原理,即从最低位到最高位进行排序的过程,并通过实例展示如何使用容器存储数据,实现对整数数组的有效排序。同时,文章提供了两种实现方式,包括基于数组和队列的方法。
1491

被折叠的 条评论
为什么被折叠?



