22、LSD 字符串排序算法

内容来自刘宇波老师算法与数据结构体系课

1、图示

image
image

2、实现 LSD

/**
 * RadixSort
 * Least Significant Digit 字符串排序算法
 * String[] arr 中, 每个字符串的长度应该相等
 * 复杂度 O(W * (N + R)) => O(n)
 */
public class LSDSort {

    private LSDSort() {
    }

    /**
     * O(W * (N + R)) => O(n)
     */
    public static void sort(String[] arr, int W) {
        for (String s : arr) {
            if (s.length() != W) throw new IllegalArgumentException("All Strings' length must be the same.");
        }

        // 字符范围 [0, 256)
        int R = 256;
        int[] cnt = new int[R];
        int[] index = new int[R + 1];
        String[] temp = new String[arr.length];

        for (int r = W - 1; r >= 0; r--) {
            // 基于第 radix 位字符进行计数排序

            Arrays.fill(cnt, 0);
            for (String s : arr) cnt[s.charAt(r)]++;

            for (int i = 0; i < R; i++) index[i + 1] = index[i] + cnt[i];

            for (String s : arr) {
                char c = s.charAt(r);
                temp[index[c]] = s;
                index[c] += 1;
            }

            System.arraycopy(temp, 0, arr, 0, temp.length);
        }
    }
}

3、总结

image
image

posted @ 2023-04-14 17:41  lidongdongdong~  阅读(31)  评论(0编辑  收藏  举报