基数排序一种基于多关键字的排序。
对多关键字进行多次排序,但是排序算法要是稳定的,否则结果会发生不可预估的错误。
如:对数字排序,先对个位排序,在对十位进行排序。。。并且可以用桶排序对每个关键字装桶。
例子:
@Override
public int[] sort(int[] source) {
int max = source[SortUtils.maxIndex(source)];
int num = getNums(max);
List<List<Integer>> list = new ArrayList<>(10);
list = initBucket(list, 10);
for (int i = 1; i <= num; i++){
source = sortByKey(list, source, i);
list = clear(list, 10);
}
return source;
}
public List<List<Integer>> initBucket(List<List<Integer>> bucket, int n){
for (int i = 0; i < n; i++){
bucket.add(new ArrayList<Integer>());
}
return bucket;
}
public List<List<Integer>> clear(List<List<Integer>> bucket, int n){
for (int i = 0; i < n; i++){
bucket.get(i).clear();
}
return bucket;
}
private int[] sortByKey(List<List<Integer>> list, int[] source, int n){
for (int i = 0; i < source.length; i++){
list.get(getLeftNNumber(source[i], n)).add(source[i]);
}
return putToArr(list, source);
}
private int[] putToArr(List<List<Integer>> list, int[] source){
int k = 0;
for (int i = 0; i < list.size(); i++){
for (int j = 0; j < list.get(i).size(); j++){
source[k++] = list.get(i).get(j);
}
}
return source;
}
private int getNums(int num){
return String.valueOf(num).length();
}
private int getLeftNNumber(int num, int n){
int sum = 1;
for (int i = 1; i < n; i++){
sum *= 10;
}
return num / sum % 10;
}