페이지

레이블이 quicksort인 게시물을 표시합니다. 모든 게시물 표시
레이블이 quicksort인 게시물을 표시합니다. 모든 게시물 표시

2012년 5월 14일 월요일

QuickSort

Java를 이용하여 String을 QuickSort하는 루틴...
Javad에서 숫자를 sorting하는 것보다, String을 sorting하는 경우에는 typecasting에 대해 신경을 더 써야한다.


    public static char [] sortString( char [] in, int low, int high ) {
   
    if( low>high )
    return in;
        int pivotPos = low + (high-low)/2;
    char pivot = in[pivotPos];
        int lowCnt = low;
        int highCnt = high;
        /*
         * Pivot 문자를 맨 뒤의 문자와 교환한다.
         * 중복 문자가 입력된 경우를 대비 
         문자 치환을 위해 Exclusive-OR를 이용하고,  그 결과를 Typecasting한다. 
        */
        in[high] = (char)(in[high] ^ in[pivotPos]);
        in[pivotPos] = (char)(in[high] ^ in[pivotPos]);
        in[high] = (char)(in[high] ^ in[pivotPos]);
     
        while( lowCnt

              /*
              * Low index에서부터  1씩 증가하며, Pivot 문자보다 뒷 순서의 문자를 찾는다.
              */

             while( in[lowCnt]
                 lowCnt++;

             while( in[highCnt]>=pivot && lowCnt
                 highCnt--;

              /*
              * High index에서부터  1씩 감소시키며, Pivot 문자보다 앞 순서의 문자를 찾는다.
              */



              /*
              * 찾은 문자를 교환한다.
              */

            if( lowCnt
                in[lowCnt] = (char)(in[lowCnt]  ^ in[highCnt]);
                in[highCnt] = (char)(in[lowCnt]  ^ in[highCnt]);
                in[lowCnt] = (char)(in[lowCnt]  ^ in[highCnt]);
                if( (lowCnt+1)
                lowCnt++;
                if( (highCnt-1)>low )
                highCnt--;
            }
           
        }
        /*
         * PLow Counter의 문자와 맨 뒤 문자를 비교하여, .
          맨 뒤에 나중 순서의 문자를 배치한다.
         * 중복 문자가 입력된 경우를 대비 
        */
        if( in[lowCnt]>in[high]) {
        in[lowCnt] = (char)(in[lowCnt] ^ in[high]);
        in[high] = (char)(in[lowCnt] ^ in[high]);
        in[lowCnt] = (char)(in[lowCnt] ^ in[high]);
        }
       
       if( (lowCnt-1)>low )
           in = sortString( in, low, lowCnt-1 );
       if( (highCnt+1)
           in = sortString( in, highCnt+1, high );
             
       return in;

    }
   
    public static String sortString( String in ) {
        int high = in.length();
        int low = 0;
        char [] out = new char [high];
        /*
         toCharArray()를 이용하여 String을 char array로 복사
         */
        out = in.toCharArray();
       
        out = sortString( out, 0, high-1 );

        /*
         copyValueOf()를 이용하여 char array의 값을 String으로 복사
         */

        return in.copyValueOf(out);
    }