Spa*_*tan 3 java arraylist while-loop insertion-sort
现在我已经有一段时间了,我遇到了一个错误.现在我正在制作的程序是一本地址簿,我正在使用插入排序对对象的arraylist进行排序,我称之为书籍(地址条目).现在我很快就发现我的分拣机没有正确排序,所以我制作了一个简单的程序来测试分拣机,而且它再次起作用.我想知道你们是否可以看看它并帮助我.
这是我的分拣机:
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我测试它的简单程序是:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
总结一下,我的ArrayList分拣机遇到了麻烦.问题是它不能正确排序,我不知道为什么.非常感谢你提前.如果您有任何问题随时问.:)
第一个问题:你期望compareTo总是为"大于"返回1.它只返回一个大于0的值,它可能是一个不同的正整数.所以你的== 1比较都应该是> 0.
可能还有其他问题,但这是我要看的第一个问题.
| 归档时间: |
|
| 查看次数: |
4133 次 |
| 最近记录: |