我在打印数组降序时遇到问题。数组顺序类似于(Title,Studio,Year)。
 我有正确的顺序,但是我不能打印升序,它只能打印降序。例

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

最佳答案

当您想要降序时,就像已经做的那样:

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


升序与降序相反,因此只需对比较进行否定即可:

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);


(您说您的排序效果很好,并且此答案假设是正确的。我尚未验证。)

09-27 20:34