我正在准备一项关于排序算法的考试。一位 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/