我是java的新手,我正在做一个需要使用合并排序的作业,但我仍然会遇到错误。我们正在使用ArrayList,这让我犯了很多错误。我发布了下面的代码以及我继续得到的错误,任何人都可以帮我弄清楚为什么会这样吗?
import java.util.ArrayList;
import java.util.UUID;
public class mSort {
public static ArrayList<String> randomList() {
ArrayList<String> a = new ArrayList<String>();
for(int i = 0; i < 10; i++) {
a.add(i, UUID.randomUUID().toString());
}
return a;
}
public void sort(ArrayList<String> list) {
sortArray(0, list.size(), list);
}
private void sortArray(int low, int high, ArrayList<String> list) {
if ((high - low) >= 1) {
int middle1 = ( low + high ) / 2;
int middle2 = middle1 + 1;
sortArray(low, middle1, list);
sortArray(middle2, high, list);
merge(low, middle1, middle2, high, list);
}
}
private void merge(int left, int middle1, int middle2, int right, ArrayList<String> list) {
int leftIndex = left;
int rightIndex = middle2;
int combinedIndex = left;
ArrayList<String> combined = new ArrayList<String>();
ArrayList<String> data = list;
while (leftIndex <= middle1 && rightIndex <= right) {
if (data.get(leftIndex).compareTo(data.get(rightIndex)) < 0) {
combined.add(combinedIndex, data.get(leftIndex));
combinedIndex++;
leftIndex++;
}
else {
combined.add(combinedIndex, data.get(rightIndex));
combinedIndex++;
rightIndex++;
}
}
if (leftIndex == middle2) {
while (rightIndex <= right) {
combined.add(combinedIndex, data.get(rightIndex));
combinedIndex++;
rightIndex++;
}
}
else {
while ( leftIndex <= middle1 ) {
combined.add(combinedIndex, data.get(leftIndex));
combinedIndex++;
leftIndex++;
}
}
for (int i = left; i <= right; i++ ) {
list.set(i, combined.get(i));
//System.out.println(list.get(i));
}
}
public static void main(String[] args) {
ArrayList<String> list = randomList();
mSort sorted = new mSort();
sorted.sort(list);
for ( int i = 0; i < list.size(); i++ ) {
System.out.println(list.get(i));
}
}
}
这里是错误的堆栈跟踪:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 0
at java.util.ArrayList.rangeCheckForAdd(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at mSort.merge(mSort.java:40)
at mSort.sortArray(mSort.java:27)
at mSort.sortArray(mSort.java:25)
at mSort.sortArray(mSort.java:26)
at mSort.sortArray(mSort.java:25)
at mSort.sort(mSort.java:17)
at mSort.main(mSort.java:74)
答案 0 :(得分:1)
这是因为你拥有的数组索引大于数组的大小减1。数组索引从0开始并转到n-1
答案 1 :(得分:1)
有几个问题。
sortArray(0, list.size(), list);
需要为sortArray(0, list.size() - 1, list);
,因为索引从0变为大小 - 1;
合并中的行combined.add(combinedIndex, data.get(rightIndex));
您无法添加到此范围0 <= index <= size
之外的索引。当你这样做时,应该根据documentation抛出一个IndexOutOfBoundsException。 (它的确如此)。这就是你看到异常的原因。组合ArrayList的大小为0,您尝试在索引3处插入
您可以将所有这些行更改为combined.add(data.get(...));
(删除combinedIndex)。不应该使用combinedIndex变量,因为数组应该已经部分排序,因此附加应该保持排序。
合并结束时下面的块alls需要更改,因此您不会超出组合数组列表的size()。如下所示。
在
for (int i = left; i <= right; i++ ) {
list.set(i, combined.get(i));
}
之后
for (int i = left; i <= right; i++ ) {
list.set(i, combined.get(i - left));
}