【发布时间】:2016-01-12 01:29:29
【问题描述】:
所以我在以下代码中收到上述错误(我的目标是递归地对我的对象进行排序并按区域排列它们)。
private static void recursionSort(ArrayList<GeometricObject> data)
{
ArrayList<GeometricObject> a = new ArrayList<GeometricObject>(data.size() / 2);
ArrayList<GeometricObject> b = new ArrayList<GeometricObject>(data.size() - a.size()); // Split array into two
// halves, a and b
for(int i = 0; i < data.size(); i++)
{
if(i < a.size())
a.set(i,data.get(i));
else
b.set(i - a.size(),data.get(i));
}
recursionSort(a); // Recursively sort first
recursionSort(b); // and second half.
int ai = 0; // Merge halves: ai, bi
int bi = 0; // track position in
while(ai + bi < data.size()) { // in each half.
if(bi >= b.size() || (ai < a.size() && a.get(ai).getArea() < b.get(bi).getArea())) {
data.set(ai + bi,a.get(ai)); // (copy element of first array over)
ai++;
} else {
data.set(ai + bi,b.get(bi)); // (copy element of second array over)
bi++;
}
}
System.out.println(data);
}
现在让我感到困惑的是我的索引从 0 开始(正确吗?)那么为什么我的索引为 0,大小为 0,我列表中的第一个对象(索引 0)肯定不是空的?有什么帮助或想法吗?谢谢!
【问题讨论】:
-
在你的递归代码中,你有没有考虑过什么是基本情况,什么是终止条件?
标签: java recursion indexing indexoutofboundsexception