java - java中LSD基数排序代码

标签 java radix-sort radix

我正在准备一项关于排序算法的考试。一位 friend 给了我这段关于 LSD 基数排序的代码,我不明白他为什么使用数字 96,97 和 64?我读过一些关于 LSD 基数排序的文章,但我不明白它是如何工作的。

public class LSDRadix {
    private static String[] list;

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.nextLine().trim());

        int size=0;
        list =new String[n];

        for(int i=0; i<n; i++){
            list[i]= sc.nextLine();

            if(size < list[i].length()){
                size = list[i].length();
            }
        }
        sort(size);

        for(int j=0; j<n;j++)
            System.out.println(list[j]);
    }

    private static void sort(int sizes){
        int numChars = 58;
        String [] aux = new String[list.length];
        int[] counter;

        for(int i=sizes-1; i>=0 ;i--){       
            counter = new int[numChars];

            for(int j=0; j<list.length; j++){
                if(list[j].length() > i){
                    if(list[j].charAt(i) >= 97)
                        counter[list[j].charAt(i)-96]++;
                    else
                        counter[list[j].charAt(i)-64]++;
                }else{
                    counter[0]++;
                }
            }

            for(int j=0; j<numChars-1; j++){
                counter[j+1] += counter[j]; 
            }

            for(int j=list.length-1; j>=0; j--){
                if(list[j].length() > i){
                    int pos;
                    if(list[j].charAt(i) >= 97){
                        pos = list[j].charAt(i)-96;
                    }else{
                        pos = list[j].charAt(i)-64;
                    }
                    aux[counter[pos]-1] = list[j];
                    counter[pos]--;
                }else{
                    aux[counter[0]-1] = list[j];
                    counter[0]--;
                }
            }

            for(int j=0; j<list.length; j++){
                list[j] = aux[j];
            }
        }   
    }
}

最佳答案

97 是字母“a”的 ASCII 值。如果测试的字符是小写字母,则从其 ASCII 值中减去 96 将得到 1 到 26 之间的数字。

否则,该字符被假定为大写字母。 65 是字母“A”的 ASCII 值,因此减去 64 将再次得到 1 到 26 之间的值。

关于java - java中LSD基数排序代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3018037/

相关文章:

algorithm - 使用最小的可能基数表示 d 位上的整数

java - Gmail 用户名和密码验证

java - 为什么我的图像缩放不正确?

c++ - 使用基数排序检查索引

java - 更改 Apache Commons Math 中数字系统的基数

c# - 有没有办法为重载运算符调用基方法? C#

java - Java中处理异常的正确方法

java - 在mysql数据库中使用servlet插入数据

java - Right (LSB) radix -- 如何处理 2 的补码?

c++ - 当我用基数2 ^ 20实现基数排序以对大小为500万的数组进行排序时,为什么该程序会陷入无限循环?