2010-06-10 5 views
0

나는 정렬 알고리즘에 관한 시험을 치르는 오전 있습니다. 친구가 LSD Radix Sorting에 대한 코드를 나에게 주었는데 왜 96,97과 64라는 숫자를 사용하고 있는지 이해할 수 없습니까? LSD 기수 정렬에 대해 몇 가지를 읽었지만 어떻게 작동하는지 이해하지 못했습니다.LSD 기수 Java의 코드를 정렬

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]; 
      } 
     } 
    } 
} 

답변

4

97은 'a'문자의 ASCII 값입니다. 테스트중인 문자가 소문자이면 ASCII 값에서 96을 뺀 값은 1에서 26 사이의 숫자가됩니다.

그렇지 않으면 문자는 대문자로 간주됩니다. 65는 문자 'A'의 ASCII 값이므로 64를 빼면 1에서 26 사이의 값이 다시 입력됩니다.

+3

오늘 두 번째로 누군가가이 OP를 통해 질문에 답하는 것을 저에게 이겼습니다! 이것은 왜 코드에 코멘트해야하는지, 그리고 명명 된 상수를 사용해야하는 이유에 대한 좋은 교훈이다. 예를 들어,'int ASCII_VALUE_OF_LOWERCASE_A = 97' 대신 코드를 97 번 던지기 만하면됩니다. – Pops

+6

상수'ASCII_VALUE_OF_LOWERCASE_A'를 도입하는 대신 문자 리터럴 'A'를 대신 사용할 수 있습니다. –

관련 문제