gpt4 book ai didi

java - CompareTo() 字符串/合并排序

转载 作者:太空宇宙 更新时间:2023-11-04 06:56:19 25 4
gpt4 key购买 nike

我在打印数组的降序时遇到问题。数组顺序类似于(标题、工作室、年份)。 我的顺序正确,但无法打印升序,它只能打印降序。示例

Movie2 a = new Movie2("布偶占领曼哈顿","哥伦比亚三星", 2001);
Movie2 b = new Movie2(“花木兰特别版”,“迪士尼”, 2004);
Movie2 c = new Movie2("怪物史莱克2", "梦工厂",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;

要选择执行此操作,您可以传入一个 boolean 值:

int result= a[ i ].getTitle().compareTo(a[ j ].getTitle()) *
(isAscending ? -1 : 1);
int result2= a[ j ].getTitle().compareTo(a[ i ].getTitle()) *
(isAscending ? -1 : 1);

(你说你的降序排序效果很好,这个答案假设这是真的。我还没有验证它。)

关于java - CompareTo() 字符串/合并排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22703008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com