【发布时间】:2019-03-11 03:18:57
【问题描述】:
晚上好,
我和我的小伙伴试图弄清楚为什么程序不会对我们输入的名称进行冒泡排序,也许有人可以暗示一下。
public static void sortDatPlane(String Ref[]){
int n = Ref.length;
int k = 1;
int j = n - 2;
int i;
while(k < n){
i = 0;
while (i <= j) {
if(notInOrder(Ref, i, i+1)){
swap(Ref, i, i+1);
}
i++;
}
k++;
}
for (String Ref1 : Ref) {
System.out.println(Ref1);
}
}
public static void swap(String Ref[], int i, int j){
String temp = Ref[i];
Ref[i] = Ref[j];
Ref[j] = temp;
}
public static boolean notInOrder(String Ref[],int i, int j){
return Ref[i].substring(0,1).compareTo(Ref[j].substring(0,1)) == 1;
}
【问题讨论】:
-
请告诉我们 swap 和 notInOrder 的作用
-
并描述出了什么问题。您预期会发生什么,结果又发生了什么?
-
@Bálint 已编辑,抱歉。它不会排序,只是作为常规列表打印 (#1 - aac #2 - aab - #3 aaa)
-
为什么只比较字符串的第一个字符?而
compareTo()并不保证只有1表示greater than- 它可以是任何正整数。
标签: java bubble-sort