RadixSort

本文通过一个详细的Java代码实例展示了基数排序算法的实现过程。从radixSort方法到辅助的getDigit、maxBits等函数,完整地解释了如何对整数数组进行排序。该算法适用于大量数据且数值范围较大的情况,具有稳定性高和不依赖元素比较的特点。
摘要由CSDN通过智能技术生成

GIF demonstration

在这里插入图片描述

Source code demonstration

import java.util.Arrays;

public class code02_RadixSort {

    public static void main(String[] args) {
        int[] array = generateRandomArray(100, 1000);
        int[] test = copyArray(array);
        Arrays.sort(test);
        radixSort(array);
        compareArray(array, test);
    }

    public static void radixSort(int[] array) {
        if (array == null || array.length < 2) {
            return;
        }
        radixSort(array, 0, array.length - 1, maxBits(array));
    }

    public static void radixSort(int[] array, int L, int R, int Digit) {
        final int Radix = 10;
        int[] bucket = new int[R - L + 1];
        for (int i = 1; i <= Digit; i++) {
            int[] count = new int[Radix];
            for (int j = L; j < R - L + 1; j++) {
                count[getDigit(array[j], i)]++;
            }
            for (int j = 1; j < count.length; j++) {
                count[j] = count[j] + count[j - 1];
            }
            for (int j = R; j >= L; j--) {
                bucket[count[getDigit(array[j], i)] - 1] = array[j];
                count[getDigit(array[j], i)]--;
            }
            System.arraycopy(bucket, 0, array, L, bucket.length);
        }
    }

    public static int maxBits(int[] array) {
        int max = Integer.MIN_VALUE;
        for (int j : array) {
            max = Math.max(max, j);
        }
        int Bits = 0;
        while (max != 0) {
            Bits++;
            max = max / 10;
        }
        return Bits;
    }

    public static int getDigit(int value, int d) {
        return (int) (value / (Math.pow(10, d - 1)) % 10);
    }

    public static int[] generateRandomArray(int maxSize, int maxValue) {
        int[] array = new int[(int) ((maxSize + 1) * Math.random())];
        for (int i = 0; i < array.length; i++) {
            array[i] = (int) (maxValue * Math.random());
        }
        return array;
    }

    public static void compareArray(int[] array1, int[] array2) {
        if (!Arrays.equals(array1, array2)) {
            System.out.println("No equals!!");
        } else {
            System.out.println("Success!!");
        }
    }

    public static int[] copyArray(int[] array) {
        int[] tmp = new int[array.length];
        System.arraycopy(array, 0, tmp, 0, array.length);
        return tmp;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值