气泡排序Java气泡排序
我面临一个问题,需要按字母顺序对字符串数组进行排序。我可以对一个数组进行排序,但当有两个数组与第一个数组相对应时,问题就开始了。每个数组中的每个值都应该位于相同的位置,以使信息不会混乱。在对array1
进行排序后,它是按字母顺序排列的,但是我不知道如何使array2
和array3
中的值在排序完成后改变位置,就像在array1
中一样
到目前为止,我的代码是:
public void sort()
{
boolean finish = false;
while(finish == false){
finish = true;
for(int i=0;i<Country.length-1;i++)
{
int num = 0;
if(Country[i] != null && Country[i + 1] != null)
{
String name1=Country[i]; String name2=Country[i+1];
num=name1.compareTo(name2);
}
else if(Country[i] == null && Country[i + 1] == null){
num = 0;
}
else if(Country[i] == null){
num = 1;
}
else {
num = -1;
}
if(num>0)
{
String temp=Country[i];
Country[i]=Country[i+1];
Country[i+1]=temp;
finish=false;
}
}
}
# 1 楼答案
如果希望根据在国家/地区数组中进行的比较来交换所有数组。您可以在一次比较后交换多个数组
通过使用交换函数,可以使在更多数组中进行交换更加简单
# 2 楼答案
到目前为止,最推荐的方法是重新设计程序,并将所有相关项目安排在一个类中。毕竟,这就是对象的用途。然后您可以创建对象
Comparable
,给它一个compareTo
方法,并对其进行排序但是,如果您确实无法做到这一点,那么您应该做的是,每当您交换排序数组中的任意两个项时,请确保交换其他数组中的相应项
因此,如果您有数组
country
、capital
和headOfState
,那么您必须编写如下内容:这样,无论何时移动主数组中的任何内容,都会在其他数组中移动相应的项,以便它们保持在一起
但是,如果你重新设计你的程序,它会更受欢迎
还要注意Java语言约定——变量名不应以大写字母开头,只应以类型名开头
# 3 楼答案
必须同时交换
Country
和City
数组中的元素