十大排序算法之九:基数排序
发布日期:2021-05-08 11:29:54 浏览次数:31 分类:精选文章

本文共 2786 字,大约阅读时间需要 9 分钟。

基数排序

原理

基数排序是一种稳定的数值排序算法,通过对数字按照一定基数进行排序来实现高效的排序。其核心思想是将一个数值的各个数字按从高到低的顺序分别进行排序,这样可以保证最终的数值按照特定基数的权重进行排序。

适用场景

基数排序在处理需要按特定基数进行排序的场景中非常有用,常见的应用场景包括手机号验证、英文单词的字母排序以及其他需要按一定基数进行比较的场景。

实现

基数排序的实现通常包括以下几个步骤:

  • 确定基数:基数的选择通常与数据的范围有关,常见的基数选择为2(二进制)、10(十进制)或者字母表的大小(如26个字母)。
  • 确定最大长度:找出数据中最长的数值长度,以便确定需要进行基数排序的具体步骤数量。
  • 对每一位进行排序
    • 计数排序:对于每一位数字,统计每个数字的出现次数。
    • 构建结果数组:根据统计结果,将数值按照指定的基数顺序排列。
  • 迭代处理:从最高位开始逐位处理,直到处理完所有位数。
  • 以下是基数排序的Java实现代码:

    import java.util.Arrays;
    public class RadixSort {
    public static void main(String[] args) {
    String[] strings = {
    "18914021920", "13223132981", "13566632981",
    "13660891039", "13361323035",
    "banana", "apple", "orange", "peach", "cherry",
    "qd", "", "abc", "qwe", "hhh", "a", "",
    "cws", "ope"
    };
    System.out.println("排序前:" + Arrays.toString(strings));
    System.out.println("排序后:" + Arrays.toString(radixSort(strings)));
    }
    private static String[] radixSort(String[] strings) {
    if (strings == null || strings.length <= 1) {
    return strings;
    }
    final int radix = 128; // ASCII 码的范围
    int maxLength = getMaxLength(strings);
    for (int i = maxLength - 1; i >= 0; i--) {
    int[] countList = new int[radix];
    for (int j = 0; j < strings.length; j++) {
    int index = getIndex(strings[j], i);
    countList[index]++;
    }
    int sum = 0;
    for (int j = 0; j < countList.length; j++) {
    countList[j] += sum;
    sum = countList[j];
    }
    String[] result = new String[strings.length];
    for (int j = strings.length - 1; j >= 0; j--) {
    int index = getIndex(strings[j], i);
    int rank = countList[index]--;
    result[rank - 1] = strings[j];
    }
    strings = result;
    }
    return strings;
    }
    private static int getIndex(String string, int i) {
    if (i <= string.length() - 1) {
    return string.charAt(i);
    } else {
    return 0;
    }
    }
    private static int getMaxLength(String[] strings) {
    int maxLength = 0;
    for (int i = 0; i < strings.length; i++) {
    if (strings[i].length() > maxLength) {
    maxLength = strings[i].length();
    }
    }
    return maxLength;
    }
    }

    测试

    通过上述代码可以看到,基数排序对输入数据进行了有效的排序。测试结果如下:

    排序前:[18914021920, 13223132981, 13566632981, 13660891039, 13361323035, banana, apple, orange, peach, cherry, qd, , abc, qwe, hhh, a, , cws, ope]
    排序后:[, , 13223132981, 13361323035, 13566632981, 13660891039, 18914021920, a, abc, apple, banana, cherry, cws, hhh, ope, orange, peach, qd, qwe]

    通过测试可以看出,基数排序能够按照指定的基数对数据进行有序排列。

    上一篇:十大排序算法之十:归并排序
    下一篇:十大排序算法之八:计数排序

    发表评论

    最新留言

    做的很好,不错不错
    [***.243.131.199]2025年04月19日 02时47分38秒