基数排序是一种非比较型整数排序算法,其原理是将整数按位数切割成不同的数字,然后按每个位数分别比较。由于整数也可以表达字符串(比如名字或日期)和特定格式的浮点数,所以基数排序也不是只能使用于整数。
- 基数排序 vs 计数排序 vs 桶排序
基数排序有两种方法:
这三种排序算法都利用了桶的概念,但对桶的使用方法上有明显差异:
基数排序:根据键值的每位数字来分配桶;
计数排序:每个桶只存储单一键值;
桶排序:每个桶存储一定范围的数值;
-
LSD 基数排序动图演示
image
package com.wei;
import java.util.Arrays;
/**
* @program: data_structure
* @description: 基数排序
* @author: wei
* @create: 2021-07-17 16:34
**/
public class Radix {
public static void main(String[] args) {
int[] array = {21,5,432,759,490,111,214};
int[][] bucket = new int[10][array.length];
int[] bucketcount = new int[10];
radixSort(array,bucket,bucketcount);
System.out.println(Arrays.toString(array));
}
public static void radixSort(int[] array,int[][] bucket,int[] bucketcount){
int max = array[0];
for(int i : array){
if(max<i){
max=i;
}
}
int maxlen = (max+"").length();
int index ;
for(int i=0,n=1;i<maxlen;i++,n*=10){
for(int j:array){
index = (j/n)%10;
bucket[index][bucketcount[index]] = j;
bucketcount[index]++;
}
int counter=0;
for(int k=0;k<10;k++){
for(int m=0;m<bucketcount[k];m++){
array[counter] =bucket[k][m];
counter++;
}
bucketcount[k]=0;
}
}
}
}