我想要按名称对此数据进行排序,我使用以下代码,任何人都可以告诉我它有什么问题吗?它没有完美地对数据进行排序。按名称排序数组
条件是我们必须使用两个while循环而仅循环。
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;
}
看到这个:http://stackoverflow.com/questions/12986386/sorting-an-array-of-strings-with-java – pcj
你的名字是阵列是一个String []? –
是否有必要使用数组?你也可以使用一个ArrayList并编写一个自定义的Comparator – Dragondraikk