只是练习一些排序算法。我尝试实现递归合并排序,但似乎为每个递归调用获取一个新的枢轴似乎存在问题。
我觉得我的代码应该可以工作......但我是使用 ArrayList 作为数据结构的新手......并且只有数组方面的经验。我需要一个动态大小的数组,所以我使用的是 ArrayList。
它只是不断吐出 pivot = 1 直到溢出:
pivot: 1
pivot: 1
pivot: 1
pivot: 1
pivot: 1
...
Exception in thread "main" java.lang.StackOverflowError
代码:
import java.util.*;
public class Sorts{
static Sorts run;
List<Integer> initialList = new ArrayList<Integer>();
public Sorts() {
//List<Integer> initialList = new ArrayList<Integer>();
initialList.add(1);
initialList.add(4);
initialList.add(8);
initialList.add(2);
initialList.add(3);
initialList.add(7);
initialList.add(9);
System.out.print("List of values: (");
for (int value: initialList) {
System.out.print(value);
}
System.out.println(")");
//output sorted array
System.out.println("Sorted list: " + mergeSort(initialList));
}
public List<Integer> mergeSort(List<Integer> list) {
if (list.size() <= 1) {
return list;
}
//after each recursion, generate two new sub lists
List<Integer> left = new ArrayList<Integer>();
List<Integer> right = new ArrayList<Integer>();
//generate new pivot for each new list
int middle = list.size()/2;
System.out.println("middle: " + middle);
int i = 0;
for (int x: list) {
if (i < middle) {
left.add(x);
}
else {
right.add(x);
}
i++;
}
//call mergeSort, passing in each new sublist (left, right)
left = mergeSort(left);
right = mergeSort(right);
return mergeLists(left, right);
}
public List<Integer> mergeLists (List<Integer> left, List<Integer> right) {
List<Integer> sortedList = new ArrayList<Integer>();
int i = 0;
while (left.size() > 0 || right.size() > 0) {
if (left.size() > 0 && right.size() > 0) {
if (left.get(i) <= right.get(i)) {
sortedList.add(left.get(i));
}
else {
sortedList.add(right.get(i));
}
}
else if (left.size() > 0) {
sortedList.add(left.get(i));
}
else if (right.size() > 0) {
sortedList.add(right.get(i));
}
}
for (int value : sortedList) {
System.out.println(value);
}
return sortedList;
}
public static void main(String []args){
run = new Sorts();
}
}
有什么想法吗?我是否错误地使用了 ArrayList?
谢谢!