2014-03-28 115 views
1

我在打印數組的降序時出現問題。數組順序如(標題,工作室,年份)。 我有正確的順序,但不能打印升序,只能打印降序。例如compareTo()字符串/合併排序

Movie2 a = new Movie2("The Muppets Take Manhattan","Columbia Tristar", 2001); Movie2 b = new Movie2("Mulan Special Edition","Disney", 2004); Movie2 c = new Movie2("Shrek2", "Dreamworks",2004);

public static void sortTitles(Movie2[] a, int low, int high) 
    { 
     if (low == high) 
      return; 

     int mid = (low + high)/2; 

     mergeTitle(a, low, mid, high); 
    } 

    public static void mergeTitle(Movie2[] a, int low, int mid, int high) 
    { 
     Movie2[] temp = new Movie2[ high - low + 1 ]; 

     int i = low, j = mid + 1, n = 0; 


     while (i <= mid || j <= high) 
     { 

      int result= a[ i ].getTitle().compareTo(a[ j ].getTitle()); 
      int result2= a[ j ].getTitle().compareTo(a[ i ].getTitle()); 
      if (i > mid) 
      { 
       temp[ n ] = a[ j ]; 
       j++; 
      } 
      else if (j > high) 
      { 
       temp[ n ] = a[ i ]; 
       i++; 
      } 
      else if (result < result2) 
      { 
       temp[ n ] = a[ i ]; 
       i++; 
      } 

      else 
      { 
       temp[ n ] = a[ j ]; 
       j++; 
      } 
      n++; 
     } 

     for (int k = low ; k <= high ; k++) 
      a[ k ] = temp[ k - low ]; 

    } // end of merge  

回答

1

當你想降序排列,因爲你已經做的:

int result= a[ i ].getTitle().compareTo(a[ j ].getTitle()); 
int result2= a[ j ].getTitle().compareTo(a[ i ].getTitle()); 

升序是下降的相反,所以只是negativize的比較:

int result= a[ i ].getTitle().compareTo(a[ j ].getTitle()) * -1; 
int result2= a[ j ].getTitle().compareTo(a[ i ].getTitle()) * -1; 

可選地做到這一點,你可以傳遞一個布爾值:

int result= a[ i ].getTitle().compareTo(a[ j ].getTitle()) * 
    (isAscending ? -1 : 1); 
int result2= a[ j ].getTitle().compareTo(a[ i ].getTitle()) * 
    (isAscending ? -1 : 1); 

(你說你的分選效果很好下降,而這個答案假設這是真的。我沒有驗證它。)