基数排序LSD
基数排序LSD
概述:
根据成员的个位数存入到有序的容器中,然后按照顺序从容器取出,之后再根据十位存入,再取出,直到成员的最大位数,得到从小到大有序。
场景分析:
21,54,87,451,12,354,61,3,64
根据成员的个位数存入到有序的容器中,
2|1,45|1,6|1,1|2,|3,5|4,35|4,6|4,8|7
然后按照顺序从容器中取出,
21,451,61,12,3,54,354,64,87
之后再根据十位存入,
03,12,21,451,54,354,61,64,87
再取出,
3,12,21,451,54,354,61,64,87
直到成员的最大位数。
003,012,021,054,061,064,087,354,451
取出
得到从小到大有序
3,12,21,54,61,64,87,354,451
JAVA实现:
package Sorts;
public class RadixSort {
public static void main(String[] args) {
int[] array = {512,4431,312,20,1};
lsdSort(array,4);
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]+",");
}
}
public static void lsdSort(int[] array, int maxlength) {
int k = 0;
int m = 1;
int n = 1;
//有序的容器,
int[][] temp = new int[10][array.length];
int[] order = new int[10];
//直到成员的最大位数,
while(m <= maxlength) {
for (int i = 0; i < array.length; i++) {
int lsd = ((array[i]/n) % 10);
//根据成员的个位数存入到有序的容器中,
temp[lsd][order[lsd]] = array[i];
order[lsd]++;
}
//然后按照顺序从容器取出,
for (int i = 0; i < 10; i++) {
if(order[i] != 0) {
for (int j = 0; j < order[i]; j++) {
array[k] = temp[i][j];
k++;
}
}
order[i] = 0;
}
k = 0;
//之后再根据十位存入,再取出,
n *= 10;
m++;
}
}
}