1

这可能是一个相当简单的问题。我只是不知道如何按降序而不是升序进行排序。谁能帮我吗?

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

2 回答 2

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 ]; 
    }
}
于 2013-05-18T20:38:26.743 回答
3

要更改排序顺序,您必须担心它们比较对象值的确切位置。在您的情况下,这在下面的行中。

只需更改此:

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

对此:

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

请注意,唯一改变的是>操作员。

于 2013-05-18T20:33:40.900 回答