首页 > 编程语言 > 详细

基数排序

时间:2019-12-29 13:01:45      阅读:71      评论:0      收藏:0      [点我收藏+]

基数排序属于稳定排序,时间复杂度为O(logRB),桶排序为基数排序的扩展

思路:将整位数切割成不同的数字,然后按每个位数分别比较

过程:设置10个桶子分别从0到9,将每个元素的个位数取出,与桶的数字相对于就放入,然后按照桶顺序依次取出数据,放入原来的数组,接着按照这个步骤取十位数,没有的补0,后面接着取百位数,千位数,同上操作,循环次数为本数组最大数的位数

import java.util.Arrays;

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 = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }

        int maxLength = (max + "").length();

        //桶排序(基数排序) 为  空间换时间的算法
        int[][] bucket = new int[10][arr.length];
        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 digitOffElement = arr[j] / n % 10;
                bucket[digitOffElement][bucketElementCounts[digitOffElement]] = arr[j];
                bucketElementCounts[digitOffElement]++;
            }
            int index = 0;
            for (int k = 0; k < bucketElementCounts.length; k++) {
                if (bucketElementCounts[k] != 0) {
                    for (int l = 0; l < bucketElementCounts[k]; l++) {
                        arr[index++] = bucket[k][l];
                    }
                }
                bucketElementCounts[k] = 0;
            }
        }
    }
}

基数排序

原文:https://www.cnblogs.com/bingbug/p/12114554.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!