2013-05-18 174 views
0

這可能是一個相當簡單的問題。我只是無法弄清楚如何按降序而不是升序進行排序。誰能幫我嗎?如何讓這種合併排序按降序而不是按升序排列?

public static void sortYear(Movie4[] movies, int low, int high) 
{ 
    if (low == high) 
     return; 
    int mid = (low + high)/2; 
    sortYear(movies, low, mid); 
    sortYear(movies, mid + 1, high); 

    mergeYears(movies, low, mid, high); 
} 

public static void mergeYears(Movie4[] movies, int low, int mid, int high) 
{ 

    Movie4[] temp = new Movie4[ high - low + 1 ]; 
    int i = low, j = mid + 1, n = 0; 
    while (i <= mid || j <= high) 
    { 
     if (i > mid) 
     { 
      temp[ n ] = movies[ j ]; 
      j++; 
     } 
     else if (j > high) 
     { 
      temp[ n ] = movies[ i ]; 
      i++; 
     } 
     else if (movies[ i ].getYear() < movies[ j ].getYear()) 
     { 
      temp[n] = movies[i]; 
      i++; 
     } 
     else 
     { 
      temp[n] = movies[j]; 
      j++; 
     } 
     n++; 
    } 
    for (int k = low ; k <= high ; k++) 
    { 
     movies[ k ] = temp[ k - low ]; 
    } 
} 
+4

是的,他是這麼說的......就在這個問題結束...... – acdcjunior

+1

這是家庭作業,但它不是全部問題。我必須使用降序合併排序編寫程序,但我無法弄清楚。看這個沒什麼問題。 – user1914491

+1

'「,所以我只是打算繼續打字」 - 是的,你不應該這樣做。 – Dukeling

回答

1

要更改排序順序,您必須考慮它們比較對象值的確切位置。在你的情況下,這是在下面的行。

只要改變這一點:

else if (movies[ i ].getYear() < movies[ j ].getYear()) 

要這樣:

else if (movies[ i ].getYear() > movies[ j ].getYear()) 

會注意到唯一改變的事情是>操作。

+0

完美!非常感謝。 – user1914491

+0

它解決了這個問題嗎?如果是這樣,你應該接受讓我們知道的答案:http://meta.stackexchange.com/a/5235/219205 – acdcjunior

5

爲了幫助您自己回答問題,我將在代碼中添加一些註釋。

所有真正的工作是在mergeYears:

public static void mergeYears(Movie4[] movies, int low, int mid, int high) 
{ 

    Movie4[] temp = new Movie4[ high - low + 1 ]; 

    // 'i' tracks the index for the head of low half of the range. 
    // 'j' tracks the index for the head of upper half of the range. 
    int i = low, j = mid + 1, n = 0; 

    // While we still have a entry in one of the halves. 
    while (i <= mid || j <= high) 
    { 
     // Lower half is exhausted. Just copy from the upper half. 
     if (i > mid) 
     { 
      temp[ n ] = movies[ j ]; 
      j++; 
     } 
     // Upper half is exhausted. Just copy from the lower half. 
     else if (j > high) 
     { 
      temp[ n ] = movies[ i ]; 
      i++; 
     } 
     // Compare the two Movie4 objects at the head of the lower and upper halves. 
     // If lower is less than upper copy from lower. 
     else if (movies[ i ].getYear() < movies[ j ].getYear()) 
     { 
      temp[n] = movies[i]; 
      i++; 
     } 
     // Lower is is greater than upper. Copy from upper. 
     else 
     { 
      temp[n] = movies[j]; 
      j++; 
     } 
     n++; 
    } 

    // Copy from the temp buffer back into the 'movie' array. 
    for (int k = low ; k <= high ; k++) 
    { 
     movies[ k ] = temp[ k - low ]; 
    } 
}