基数排序
介绍
- 1基数排序(radix sort)属于“分配式排序”(distribution sort),又称“桶子法”(bucket sort)或 bin sort,顾名思义,它是通过键值的各个位的值,将要排序的元素分配至某些“桶”中,达到排序的作用;
- 2基数排序法是属于稳定性的排序,基数排序法的是效率高的稳定性排序法;
- 3基数排序(Radix Sort)是桶排序的扩展;
思想
可参考https://www.bilibili.com/video/BV1wa4y177rX?from=search&seid=780482739292305673
代码实现
public class RadixSort {
public static void main(String[] args) {
int[] array = {53, 3, 542, 748, 14, 214};
int[] temp = new int[array.length] ;
System.out.println(getMaxPlace(array));
radixSort(array);
for (int i : array) {
System.out.print(i+" ");
}
System.out.println();
}
// 基数排序方法
public static void radixSort(int[] arr) {
// 定义十个装数据的桶
int[][] bucket = new int[10][arr.length];
// 定义一个一维数组保存每个桶的下标
int[] indexArray = new int[10];
// 获取最大的数有几位
int maxPlace = getMaxPlace(arr);
// 计算10的i次方的数
int n = 1;
for (int i = 0; i < maxPlace; i++) {
// 将数据放入桶中
for (int j = 0; j < arr.length; j++) {
// 取第N位的算法: arr[j] / (10的i次方) % 10
int temp = arr[j] / (n) % 10;
bucket[temp][(indexArray[temp])] = arr[j];
// 对应下标后移
indexArray[temp]++;
}
// 走完一轮n*10
n *= 10;
// 将桶中数据回写到array中
int count = 0;
for (int j = 0; j < indexArray.length; j++) {
if (count < arr.length){
for (int k = 0; k < indexArray[j]; k++) {
arr[count] = bucket[j][k];
count++;
}
indexArray[j] = 0;
}
}
}
}
// 判断最大的数有几位
public static int getMaxPlace(int[] array){
int max = array[0];
for (int i : array) {
if (max <= i){
max = i;
}
}
return (max+"").length();
}
}