【发布时间】:2015-05-13 11:52:27
【问题描述】:
我希望这些数据按名称排序,我正在使用以下代码,谁能告诉我它有什么问题?它没有完美地对数据进行排序。
条件是我们只能使用两个while和if循环。
Sales and Commission
======================================================
Salesperson Sales Amount Commission
-----------------------------------------------------
h h $54000 $4320.0
jghu jghf $90000 $9000.0
hg gf $45000 $2700.0
kaushal garg $87000 $8700.0
kfhfuyd dhd $32000 $1920.0
Total: 9 Data entries
代码:
public static void sortByName() {
int small; // Two while loop and one if loop for sorting
int i = 0; // the data based on sales amount
while (i < name.length) {
small = i;
int index = i + 1;
while (index < name.length) {
if (name[index].compareToIgnoreCase(name[small]) < 0) { // name comparision for sorting
small = index;
}
swap(i, small); // caling the swap method
index++;
}
i++;
}
displayData(); // calling displayData function.
}
//Method used in the sorting the data based on name and sales
public static void swap(int first, int second) {
String temp = name[first];
name[first] = name[second];
name[second] = temp;
}
【问题讨论】:
-
你的名字数组是String[]吗?
-
有必要使用数组吗?您还可以使用 ArrayList 并编写自定义 Comparator
-
“条件是我们必须使用两个 while 和 if 循环”:谁告诉你这个?顺便问一下,什么是 if 循环?
-
@user714965 可能是老师