[英]Trouble with Properly Sorting Array in Alphabetical Order
我的部分代码有问题。 它必须按名称按字母顺序排序,但似乎是以降序方式进行的。 有人可以指导我进行哪些更改,以使输出正确显示数据吗? 谢谢。
这是我的排序代码:
//Method sortName
public static void sortName() throws IOException {
//Selection Sort
for (x = 0; x < 8; x++) {
smallest = x;
for(i = x + 1; i < 8; i++) {
//Compare current smallest
//to the current position in the array
if(name[i].compareTo(name[smallest])> 0) {
smallest = i;
}
}
//Swap smallest element with position in array
temp = name [x];
name [x] = name [smallest];
name [smallest] = temp;
temp = crime [x];
crime [x] = crime [smallest];
crime [smallest] = temp;
temp = year [x];
year [x] = year [smallest];
year [smallest] = temp;
}
//Display each category of records; names, crime, year
System.out.print("Name" + " ----" + "Crime" + "----" + "Year\n");
//output
for (x = 0; x < 8; x++) {
//Display each sorted criminal name with the crime and year.
System.out.println(name[x] + " --- " + crime[x] + " --- " + year[x]);
这是我的输出:
Name ----Crime----Year
Slippery Sal --- Arson --- 1997
Natasha Ora --- Theft --- 2007
Kate Olaf --- Assault --- 1984
Eddie Striker --- Arson --- 1978
Bugs Malone --- Theft --- 1981
Bob Allen --- Assault --- 1957
Anne Wilson --- Arson --- 2013
看看compareTo
javadoc 。 它指出:
返回:负整数,零或正整数,因为此对象小于,等于或大于指定的对象。
在你的行
if(name[i].compareTo(name[smallest])> 0) {
提到的“此对象”是name[i]
,“指定对象”是name[smallest]
。 并且您想在name[i]
小于 name[smallest]
时进行交换。 因此,要么交换name[i]
和name[smallest]
,要么将比较值更改为< 0
。
我也总是建议在第一次测试时,特别是在出现意外行为时,逐步使用调试器执行代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.