我在java中编写合并排序类,当我到达sort(left)
行时,我收到堆栈溢出错误。有什么想法吗?我不明白为什么这会是一个问题。
包ds;
import java.util.Comparator;
public class MergeSorter<T> extends Sorter<T> {
public MergeSorter(Comparator<T> comparator){
super(comparator);
}
@SuppressWarnings("unchecked")
@Override
public void sort(T[] array){
if (array.length <= 1);
else {
T[] left = (T[]) new Object[array.length/2 + 1];
T[] right = (T[]) new Object[array.length/2 + 1];
int middleIndex = array.length / 2;
for (int i = 0; i < middleIndex; i++) {
left[i] = array[i];
}
for (int i = middleIndex; i < array.length; i++) {
right[i - middleIndex] = array[i];
}
sort(left);
sort (right);
merge(left, right, array);
}
}
public final void merge(T[] left, T[] right, T[] array){
Array<T> sortedArray = new Array<T>(array.length);
while (left.length > 0 || right.length > 0) {
if (left.length > 0 && right.length > 0) {
if (comparator.compare(left[0], right[0]) < 0) {
sortedArray.add(left[0]);
for (int i = 1; i < left.length; i++) {
left[i - 1] = left[i];
left[left.length - 1] = null;
}
}
else {
sortedArray.add(right[0]);
for (int i = 1; i < right.length; i++) {
right[i - 1] = right[i];
right[right.length - 1] = null;
}
}
}
else if (left.length > 0) {
sortedArray.add(left[0]);
for (int i = 1; i < left.length; i++) {
left[i - 1] = left[i];
left[left.length - 1] = null;
}
}
else if (right.length > 0) {
sortedArray.add(right[0]);
for (int i = 1; i < right.length; i++) {
right[i - 1] = right[i];
right[right.length - 1] = null;
}
}
}
for (int i = 0; i < array.length; i++) {
array[i] = sortedArray.get(i);
}
}
}
答案 0 :(得分:1)
假设数组的长度为2
。然后左边是:
T[] left = (T[]) new Object[array.length/2 + 1];
是
T[] left = (T[]) new Object[2/2 + 1];
,这相当于
T[] left = (T[]) new Object[2];
当您对left
进行排序时,这会继续,并导致无限递归,这可能导致您发布的堆栈溢出错误。
由于您要将第一个middleIndex
元素复制到left
,因此middleIndex
长度应该适合数组left
。因此left
应该是长度为array.length/2
的数组。