22、LSD 字符串排序算法
1、图示
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、总结
本文来自博客园,作者:lidongdongdong~,转载请注明原文链接:https://www.cnblogs.com/lidong422339/p/17319099.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步