基数排序的java实现

package com.edu.hpu.sort.radix;

import java.util.LinkedList;
import java.util.List;

import com.edu.hpu.sort.Sort;

public class RadixSort extends Sort {
    private int radix;
    private int d;
    public RadixSort(int radix, int d) {
        this.radix = radix;
        this.d = d;
    }
    @Override
    public int[] doSort(int[] arr) {
        List<Integer>[] bucket = init(radix);
        int [] tmp = new int [arr.length];
        // 控制数字的位
        for(int i = 0; i < d; i++){
            // 取得位数每个数的某一位
            for(int v : arr){
                int d = (int) (v / Math.pow(10, i) % 10);
                bucket[d].add(v);
            }
            // 各个位进行桶排序的结果放入tmp中
            for(int w = 0, j = 0; j < bucket.length && w < tmp.length; j++){
                for(int v : bucket[j]){
                    tmp[w] = v;
                    w++;
                }
            }
            // 处理数组
            arr = tmp;
            for(List<Integer> l : bucket){
                l.clear();
            }
        }
        return arr;
    }
    // 初始化桶
    private List<Integer> [] init(int range){
        @SuppressWarnings("unchecked")
        List<Integer> [] aux = new LinkedList[range];
        for(int i = 0; i < aux.length; i++){
            aux[i] = new LinkedList<Integer>();
        }
        return aux;
    }
    public static void main(String[] args) {
        Sort sort = new RadixSort(10, 3);
        sort.printOrder(new int []{4, 1, 3, 2, 16, 101, 43,200,999,9, 100, 194, 8, 7});
    }
}
原文地址:https://www.cnblogs.com/xinyuyu/p/4788085.html