我正在用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);
}
}
}