您的位置:首页 > 编程语言

基本排序算法--基数排序(参考桶排序,此处只复制代码)

2018-02-20 18:33 211 查看
package poly;

import java.util.Arrays;

//基数排序

public class RadixSort {

public static void main(String[] args) {
int[] array = {1100, 192, 221, 12, 13};
RadixSort t = new RadixSort();
t.sort(array, 10, 4);
System.out.println(Arrays.toString(array));
}
/**
* @方法功能说明:  基数排序
* @创建:2018年2月20日 by 北岳
* @param array : 待排序数组
* @param radix : 基数
* @param d     : 最高位数
* @return void     
* @throws
*/
public void sort(int[] array, int radix, int d) {
        //数组长度
        int length = array.length;
        //存放临时数据
        int[] data = new int[length];
        //桶数据
        int[] temp = new int[10];

        for (int i = 0, rate = 1; i < d; i++) {
            //保证桶干净
            Arrays.fill(temp, 0);

            for (int j = 0; j <  length; j++) {
                    int key = (array[j] / rate) % radix;
                    temp[key] ++;
            }

            for (int j = 1; j < temp.length; j++) {
                    temp[j] = temp[j] + temp[j - 1];
            }

            System.arraycopy(array, 0, data, 0, length);

            for (int m = length - 1; m >= 0; m--) {
                    int key = (data[m] / rate) % radix;
                    array[--temp[key]] = data[m];
            }

            System.out.println("第" + rate + "位排序 : " + Arrays.toString(array));
            rate *= radix;
        }
    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐