排序_基数排序

代码

/**
 * 基本思想: 将所有待比较数值(正整数)统一为同样的数位长度,数位较短的数前面补零。然后,从最低位开始,依次进行一次排序。
 * 这样从最低位排序一直到最高位排序完成以后,数列就变成一个有序序列。
 * 
 * @author yeoggc
 *
 */
public class 基数排序code_1 {

    private void sort(int[] array) {
        // 找到最大值(用于确定排序需要几趟)
        int max = 0;
        for (int i = 0; i < array.length; i++) {
            if (max < array[i]) {
                max = array[i];
            }
        }

        // 计算位数
        int times = 0;
        while (max > 0) {
            max = max / 10;
            times++;
        }

        // 建立十个队列
        List<ArrayList<Integer>> queueList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            queueList.add(new ArrayList<>());
        }

        // 进行times次分配和排序
        for (int i = 0; i < times; i++) {
            // 循环数组中每个元素,把符合条件的元素放到对应队列上
            for (int j = 0; j < array.length; j++) {
                int x = array[j] % (int) Math.pow(10, i + 1) / (int) Math.pow(10, i);
                ArrayList<Integer> queueList2 = queueList.get(x);
                queueList2.add(array[j]);
                queueList.set(x, queueList2);
            }

            int count = 0;//记录修改原数组的位置
            //按1到10顺序从queueList去对应的队列,然后把队列中每个元素取出,赋值到源数组。
            for (int j = 0; j < 10; j++) {
                ArrayList<Integer> queueList3 = queueList.get(j);
                while (queueList3.size() > 0) {
                    array[count] = queueList3.remove(0);
                    count++;
                }

            }

        }

    }

    public static void main(String[] args) {
        // 待排序的序列
        int a[] = { 49, 38, 65, 97, 176, 213, 227, 49, 78, 34, 12, 164, 11, 18, 1 };
        基数排序code_1 sort = new 基数排序code_1();
        System.out.println("排序之前:");
        sort.printPart(a);
        // 基数排序
        sort.sort(a);
        System.out.println("排序之后:");
        sort.printPart(a);
    }

    // 打印序列
    public void printPart(int[] list) {
        for (int i = 0; i < list.length; i++) {
            System.out.print(list[i] + " ");
        }
        System.out.println();
    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容