跳到主要内容

20、数据结构和算法 - 实战:基数排序算法

基数排序 (Radix Sort) 是一种非比较型整数排序算法,其原理是将整数按位数切割成不同的数字,然后按每个位数分别比较。基数排序的发明可以追溯到 1887 年赫尔曼·何乐礼在打孔卡片制表机 (Tabulation Machine)上的贡献。

基数排序法会使用到桶 (Bucket),顾名思义,通过将要比较的位(个位、十位、百位…),将要排序的元素分配至 0~9 个桶中,借以达到排序的作用,在某些时候,基数排序法的效率高于其它的比较性排序法。

1.2 算法基本思想

将所有待比较数值(正整数)统一为同样的数位长度,数位较短的数前面补零

从最低位开始,依次进行一次排序

从最低位排序一直到最高位排序完成以后, 数列就变成一个有序序列

 

1.3 基数排序复杂度分析

1、 时间复杂度:;
每一次关键字的桶分配都需要O(n)的时间复杂度,而且分配之后得到新的关键字序列又需要O(n)的时间复杂度。
假如待排数据可以分为d个关键字,则基数排序的时间复杂度将是O(d2n) ,当然d要远远小于n,因此基本上还是线性级别的。
系数2可以省略,且无论数组是否有序,都需要从个位排到最大位数,所以时间复杂度始终为O(d
n) 。其中,n是数组长度,d是最大位数。 2、 空间复杂度:基数排序的空间复杂度为O(n+k),其中k为桶的数量,需要分配n个数;

1.4 基数排序代码实现

package com.yuanxw.datastructure.chapter20;

import java.util.Arrays;

/**
 * 基数排序(radix sort)属于“分配式排序”(distribution sort),又称“桶子法”(bucket sort)或bin sort,顾名思义,它是透过键值的部份资讯,
 * 将要排序的元素分配至某些“桶”中,藉以达到排序的作用,基数排序法是属于稳定性的排序,其时间复杂度为O (nlog(r)m),
 * 其中r为所采取的基数,而m为堆数,在某些时候,基数排序法的效率高于其它的稳定性排序法。
 */
public class RadixSort {
   
     
    public static void main(String[] args) {
   
     
         int[] array = {
   
     53, 3, 542, 748, 14, 214};
        System.out.println("【基数排序】前的结果:" + Arrays.toString(array));
        radixSort(array);
        System.out.println("【基数排序】后的结果:" + Arrays.toString(array));
    }

    public static void radixSort(int[] array) {
   
     
        // 1.找到最大的数
        int maxNumber = array[0];
        for (int i = 1; i < array.length; i++) {
   
     
            if (maxNumber < array[i]) {
   
     
                maxNumber = array[i];
            }
        }

        // 2.获得最大数的位数
        int maxLength = String.valueOf(maxNumber).length();

        // 3.设置两维数组[10][maxLength],10个桶,每个桶的最大长度为maxLength
        int[][] bucket = new int[10][maxLength];
        // 4.定义一个一维数组,记录每个桶的元素。
        int[] bucketElementCount = new int[bucket.length];
        // 5.依次循环获数据个位、十位、百位...放存到桶中。不足位的放到的0桶中。
        for (int i = 0, n = 1; i < maxLength; i++, n *= 10) {
   
     
            for (int index = 0; index < array.length; index++) {
   
     
                int number = array[index];
                int digit = Math.abs(number / n % 10);

                // bucketElementCount[digit]获得桶的个数,默认0
                bucket[digit][bucketElementCount[digit]] = number;
                bucketElementCount[digit]++;
            }

            // 6.将每个桶中的数据取,重新赋值到的原始数组中,完成一轮排序。
            int arrayIndex = 0;
            for (int index = 0; index < bucketElementCount.length; index++) {
   
     
                if (bucketElementCount[index] != 0) {
   
     
                    for (int k = 0; k < bucketElementCount[index]; k++) {
   
     
                        array[arrayIndex++] = bucket[index][k];
                    }
                }
                bucketElementCount[index] = 0;
            }
        }
    }
}

执行结果:

【基数排序】前的结果:[53, 3, 542, 748, 14, 214]
【基数排序】后的结果:[3, 14, 53, 214, 542, 748]