一、基数排序
/**
* 基数排序:
* 基数排序是把整数按位次从右到左(从低位到高位)切割成个位数,然后按照每个位数进行比较。
* 所以我们需要先找出最长的那个数,那个数的长度就是我们需要比较的次数。其他数长度不够逻辑补0。
*/
public class _8_RadixSort {
public static void main(String[] args) {
Integer[] arr = {3, 5, 1, 7, 2, 3, 4, 8};
radixSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void radixSort(Integer[] arr) {
//找出数组中长度最长的数
int max = Integer.MIN_VALUE;
for (int num : arr) {
if (num > max) {
max = num;
}
}
//计算最大数字是几位数
int maxLen = (max + "").length();
//用于临时存储数据,x轴是0~9,y轴是当前循环中某位次在某一个x上的个数,y的最大值是arr.length
int[][] temp = new int[10][arr.length];
//用于存储本次循环中0~9上有几个数
int[] counts = new int[10];
//根据最大长度数的位数来决定比较次数
for (int i = 0, n = 1; i < maxLen; i++, n *= 10) {
//比较数组中的每个数
for (int j = 0; j < arr.length; j++) {
//计算余数
int remainder = arr[j] / n % 10;
//把当前数放进temp中存储
temp[remainder][counts[remainder]] = arr[j];
//记录数量
counts[remainder]++;
}
//记录取出来的元素放的位置
int idx = 0;
//取出每个数
for (int j = 0; j < counts.length; j++) {
//如果当前counts不为0,说明里面有数需要取
if (counts[j] != 0) {
//循环取出数
for (int k = 0; k < counts[j]; k++) {
arr[idx] = temp[j][k];
//记录下个位置
idx++;
}
}
//把数量清空
counts[j] = 0;
}
}
}
}