现在我已经做了一段时间了,但我遇到了一个错误。现在我正在制作的程序是一个地址簿,我正在使用插入排序对我称之为书籍(地址条目)的对象数组列表进行排序。现在我很快发现我的分拣机没有正确分拣,所以我编写了一个简单的程序来测试分拣机,但它再次不起作用。我想知道你们是否可以看看它并帮助我。
这是我的分拣机:
import java.util.ArrayList;
public class Sorts {
/**
* Sorts and array of integer from low to high
* pre: none
* post: Integers has been sorted from low to high
*/
public static void insertionSort(ArrayList<String> test) {
Comparable temp;
int previousIndex;
ArrayList<String> objectSort = test;
for (int i = 1; i < objectSort.size(); i++) {
temp = objectSort.get(i);
previousIndex = i - 1;
while ((objectSort.get(previousIndex).compareTo((String) temp)) == 1 && (previousIndex > 0)) {
objectSort.set(previousIndex + 1, objectSort.get(previousIndex));
previousIndex -= 1; //decrease index to compare current item with next previous item
}
if (objectSort.get(previousIndex).compareTo((String) temp) == 1) {
/* shift item in first element up into next element */
objectSort.set(previousIndex + 1, objectSort.get(previousIndex));
/* place current item at index 0 (first element */
objectSort.set(previousIndex, (String) temp);
} else {
/* place current item at index ahead of previous item */
objectSort.set(previousIndex + 1, (String) temp);
}
}
}
}
我用来测试它的简单程序是:
import java.util.ArrayList;
public class Main {
public static void main(String[] args){
ArrayList<String> test = new ArrayList<String>();
test.add("Roxy");
test.add("Proxy");
test.add("Moxy");
test.add("Samuel Adams");
Sorts.insertionSort(test);
System.out.println(test);
}
}
总而言之,我的 ArrayList 排序器有问题。问题是它不会正确排序,我不知道为什么。非常感谢你提前。如果你有任何问题随时问。 :)
最佳答案
第一个问题:您期望 compareTo
总是为“大于”返回 1。它只是返回一个大于 0 的值,它可能是一个不同的正整数。所以你的 == 1
比较应该是 > 0
。
可能还有其他问题,但这是我首先要考虑的问题。
关于java - 插入排序排序一个ArrayList的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11091537/