【发布时间】:2013-05-05 03:17:17
【问题描述】:
我正在为一个学校项目研究某种算法,但我遇到了一个问题。 下面的代码它没有对数组进行排序,我尝试了使用数字数组的相同代码(唯一的变化是在 if 中)并且它正在工作但现在使用 String 数组并且使用 compareTo 它不起作用它只是把项目以“随机”顺序排列。
public static void selectionSortISBN(Book pin[], int booksCounter) {
for (int x = 0; x < booksCounter; x++) {
int minIndex = x;
for (int y = x + 1; y < booksCounter; y++) {
if (pin[y].getISBN().compareTo(pin[minIndex].getISBN()) < 0) {
minIndex = y;
}
}
Book temp = pin[x];
pin[x] = pin[minIndex];
pin[minIndex] = temp;
}
}
编辑:
我改变了我的内心:
for (int y = x + 1; y < booksCounter; y++) {
int com=pin[y].getISBN().compareTo(pin[minIndex].getISBN());
System.out.println(pin[y].getISBN()+" "+pin[minIndex].getISBN()+" = "+com);
}
我得到的输出是这个
1537 1485 = 1
596 1485 = 4
1164 1485 = -3
909 1485 = 8
596 1537 = 4
1164 1537 = -4
909 1537 = 8
1164 596 = -4
909 596 = 4
909 1164 = 8
【问题讨论】:
-
代码看起来没问题。你检查过输入值吗?特别是,我会删除
booksCounter并改用pin.length -
您确定订单是“随机”的吗?可以发一个输入输出的例子吗?
-
您是按 ISBN 的字母数字排序,而不是按标题排序,您知道吗?它们真的是由 ISBN “随机”订购的吗? “getISBN”有什么作用?也许这个函数没有返回正确的值。
-
@SJuan76 我不使用 pin.lenght 因为数组并不总是满的。
-
@svinja 是的,我知道,我需要为存储在字符串中的 ISBN 和标题执行算法
标签: java string algorithm sorting