我打印出数组降序的问题。数组顺序如(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
答案 0 :(得分:1)
当你想要降序时,就像你已经做的那样:
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);
(你说你的排序效果很好,这个答案假设是真的。我还没有验证过。)