我写了一个简单的插入排序算法的乐趣。它看起来工作得很好,只有一个问题,它只适用于数组中所有项目(它试图排序的东西)都是单个数字的整数。如果一个元素是一个多位整数,它将所有东西都整理到整数,然后停止并抛出一个IndexOutOfBoundsException.
为什么我的插入排序算法只能使用单个数字的整数?
注意:为了让您了解源代码,我的程序工作方式如下所示: InsertionSort
class a primative int
array in construction。然后我将其转换为ArrayList list
。我知道ArrayList list
有正确的值被复制,因为我打印出来并匹配。
示例运行:
工作:
{ 9, 2, 8, 5, 1, 6, 6, 7, 1}; //works perfectly
- >
Unsorted List: [9, 2, 8, 5, 1, 6, 6, 7, 1]
Step 1: [9]
Step 2: [2, 9]
Step 3: [2, 8, 9]
Step 4: [2, 5, 8, 9]
Step 5: [1, 2, 5, 8, 9]
Step 6: [1, 2, 5, 6, 8, 9]
Step 7: [1, 2, 5, 6, 6, 8, 9]
Step 8: [1, 2, 5, 6, 6, 7, 8, 9]
Step 9: [1, 1, 2, 5, 6, 6, 7, 8, 9]
Sorted List: [1, 1, 2, 5, 6, 6, 7, 8, 9]
不工作:
{ 9, 2, 8, 5, 1, 6, 6, 7, 1, 22, 823, 30, 244, 45, 5}; //doesn't work
- >
Unsorted List: [9, 2, 8, 5, 1, 6, 6, 7, 1, 22, 823, 30, 244, 45, 5]
Step 1: [9]
Step 2: [2, 9]
Step 3: [2, 8, 9]
Step 4: [2, 5, 8, 9]
Step 5: [1, 2, 5, 8, 9]
Step 6: [1, 2, 5, 6, 8, 9]
Step 7: [1, 2, 5, 6, 6, 8, 9]
Step 8: [1, 2, 5, 6, 6, 7, 8, 9]
Step 9: [1, 1, 2, 5, 6, 6, 7, 8, 9]
java.lang.IndexOutOfBoundsException: Index: 9, Size: 9
Sorted List: [1, 1, 2, 5, 6, 6, 7, 8, 9]
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at InsertionSort.sort(InsertionSort.java:41)
at Executer.main(Executer.java:7)
下面是相关的排序代码:
static ArrayList<Integer> list = new<Integer> ArrayList();
static ArrayList<Integer> list2 = new<Integer> ArrayList();
public static int[] sort() {
int s = 0;
System.out.println("Unsorted List: " + list.toString());
try {
for (int i = 0; i < list.size(); i++) {
s++;
if (i == 0) {
list2.add(list.get(i));
System.out.println("Step " + s + ": " + list2.toString());
continue;
} else {
int z = 0;
while (list2.get(z) < list.get(i)) {
z++;
}
list2.add(z, list.get(i));
}
System.out.println("Step " + s + ": " + list2.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Sorted List: " + list2.toString());
return toPrimative(list.toArray(new Integer[list.size()]));
}
听起来像是你应该做一些调试... –
@OliverCharlesworth我尝试添加一些打印报表的事情。我也读过关于ArrayList的JavaDoc。说实话,我真的不知道如何使用eclipse调试器。你能推荐一个调试程序吗? (在哪里添加打印语句等) –
学习使用调试器与学习语言一样重要。花点时间。 http://www.tutorialspoint.com/eclipse/eclipse_debugging_program.htm – OldProgrammer