如何使此合并排序按降序而不是升序?

时间:2013-05-18 20:23:47

标签: java mergesort

这可能是一个相当简单的问题。我只是无法弄清楚如何按降序而不是升序进行排序。任何人都可以帮助我吗?

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 ]; 
    }
}

2 个答案:

答案 0 :(得分: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 ]; 
    }
}

答案 1 :(得分:1)

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

只需改变一下:

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

对此:

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

请注意,唯一改变的是>运算符。