I'm trying to get some practice with sorting in Java.
I'm working on the merge sort now... Eclipse is outputting Out Of Memory Error: Java Heap space
, but I'm not sure how to debug that.
I feel like my code is okay- any thoughts?
import java.util.ArrayList;
import java.util.List;
public class Sorts {
List<Integer> initialList;
public Sorts() {
initialList = new ArrayList<Integer>();
initialList.add(2);
initialList.add(5);
initialList.add(9);
initialList.add(3);
initialList.add(6);
System.out.print("List: [");
for (int values : initialList) {
System.out.print(values);
}
System.out.println("]");
splitList(initialList);
}
public List<Integer> splitList(List<Integer> splitMe) {
List<Integer> left = new ArrayList<Integer>();
List<Integer> right = new ArrayList<Integer>();
if (splitMe.size() <= 1) {
return splitMe;
}
int middle = splitMe.size()/2;
int i = 0;
for (int x: splitMe) {
if (i < middle) {
left.add(x);
}
else {
right.add(x);
}
i++;
}
left = splitList(left);
right = splitList(right);
return mergeThem(left, right);
}
public List<Integer> mergeThem(List<Integer> left, List<Integer> right) {
List<Integer> sortedList = new ArrayList<Integer>();
int x = 0;
while (left.size() > 0 || right.size() > 0) {
if (left.size() > 0 && right.size() > 0) {
if (left.get(x) > right.get(x))
sortedList.add(left.get(x));
else
sortedList.add(right.get(x));
}
else if (left.size() > 0) {
sortedList.add(left.get(x));
}
else if (right.size() > 0) {
sortedList.add(right.get(x));
}
}
return sortedList;
}
}