2011-12-10 2 views
0

mergesort를 사용하여 Java에서 String 배열을 정렬 할 수있는 방법을 만들고 싶습니다. 일부 코드 샘플을보고 자체 알고리즘을 만들었지 만 작동하지 않는 것으로 보이고 문제를 찾는 데 어려움이 있습니다. 코드는 다음과 같습니다 :Java Mergesort strings

/* 
* Sorting methods, implemented using mergesort to sort the array of names 
* alphabetically 
*/ 
public String[] sort(String[] array) { 
    // check if the number of elements < 2 
    if (array.length > 1) { 

     // divide into two smaller arrays 
     // determine length of two smaller arrays 
     int arrLen1 = array.length; 
     int arrLen2 = array.length - arrLen1; 

     // populate smaller arrays with elements from initial array 
     String[] array1 = new String[arrLen1]; 
     String[] array2 = new String[arrLen2]; 

     for (int i = 0; i < arrLen1; i++) { 
      array[i] = array1[i]; 
     } 

     for (int i = arrLen1; i < array.length; i++) { 
      array[i] = array2[i]; 
     } 

     // now that we have the two halves, we can recursively call sort() on each to sort them 
     array1 = sort(array1); 
     array2 = sort(array2); 

     // three counters are needed to keep track of where we are in the arrays, one for pos in final array, and one for each of the two halves 
     // i => pos in main array 
     // j => pos in array1 
     // k => pos in array2 
     int i = 0, j = 0, k = 0; 

     while (array1.length != j && array2.length != k) { 
      if (array1[i].compareTo(array2[i]) < 0) { 
       // copy current element of array1 to final array as it preceeds array2's current element 
       array[i] = array1[j]; 

       // increment the final array so we dont overwrite the value we just inserted 
       i++; 
       // increment array1 which we took the element from so we dont compare it again 
       j++; 
      } 
      // If the element in array2 preceeds the element in array1 

      else { 
       // copy current element of array1 to final array as it preceeds array1's current element 
       array[i] = array2[j]; 
       // increment the final array so we dont overwrite the value we just inserted 
       i++; 
       // increment array2 which we took the element from so we dont compare it again 
       k++; 
      } 
     } 

     // at this point one of the sub arrays have been exhausted, and no more elements to compare 
     while (array1.length != j) { 
      array[i] = array1[j]; 
      i++; 
      j++; 
     } 

     while (array2.length != k) { 
      array[i] = array2[k]; 
      i++; 
      k++; 

     } 
    } 

    return array; 
} 
+0

각 정렬 호출에서 로깅을 추가하고 어떻게 작동해야하는지 알 수있는 작은 배열로 테스트 해보십시오. –

답변

0

실제로 비교하기 전에 재귀 적으로 정렬하려고하는 코드입니다.

코드가 작성된 방식으로 array1은 항상 array와 같고 array1에 다시 정렬을 지정합니다. 즉, 원을 계속 순환합니다.