zoukankan      html  css  js  c++  java
  • 数据结构-桶排序

    一. 定义

    将所有待比较数值统一为同样的数位长度, 数位较短的数前面补零。 然后, 从最低位开始, 依次进行一次排序。
    这样从最低位排序一直到最高位排序完成以后, 数列就变成一个有序序列。

    二. 图文说明


    三. 代码实现

    public class RadixSort {
    
        public static void main(String[] args) {
            int arr[] = {53, 3, 542, 748, 14, 214};
            radixSort(arr);
            System.out.println(Arrays.toString(arr));
    
        }
    
    
        public static void radixSort(int[] arr) {
            //取的最大数的位数
            int max = arr[0];
            for (int i = 0; i < arr.length; i++) {
                max = Math.max(arr[i], max);
            }
            int maxLength = (max + "").length();
            //定义一个二维数组,表示10个桶
            int[][] bucket = new int[10][arr.length];
            //为了记录每个桶中,实际存放了多少个数据,定义一个一维数组来记录各个桶的每次放入的数据个数
            //比如: bucketElementCounts[0] , 记录的就是 bucket[0] 桶的放入数据个数
            int[] bucketElementCounts = new int[10];
            for (int i = 0, n = 1; i < maxLength; i++, n *= 10) {
                //(针对每个元素的对应位进行排序处理), 第一次是个位, 第二次是十位, 第三次是百位
                for (int j = 0; j < arr.length; j++) {
                    int digitOfElement = arr[j] / n % 10;
                    bucket[digitOfElement][bucketElementCounts[digitOfElement]] = arr[j];
                    bucketElementCounts[digitOfElement]++;
                }
                //取出数据
                int index = 0;
                for (int k = 0; k < bucketElementCounts.length; k++) {
                    if (bucketElementCounts[k] != 0) {
                        for (int j = 0; j < bucketElementCounts[k]; j++) {
                            arr[index++] = bucket[k][j];
                        }
                    }
                    bucketElementCounts[k] = 0;
                }
            }
        }
    }
    
  • 相关阅读:
    svn 更新
    首尾渐变
    sublime常用快捷键
    【CSS3】transition过渡和animation动画
    JS实现奇偶数的判断
    style、currentStyle、getComputedStyle区别介绍
    JavaScript中判断对象类型的种种方法
    CSS3 animation动画,循环间的延时执行时间
    EMCA创建em资料库时报错
    OS Kernel Parameter.semopm
  • 原文地址:https://www.cnblogs.com/gcm688/p/14745261.html
Copyright © 2011-2022 走看看