I'm attempting to implement quicksort in java in order to count the number of comparisons made, but I'm running into an infinite loop/recursive call situation, and I can't quite figure out where it's coming from.
Through debugging I've determined that the inner for loop runs however many times, and everything is only entered into "less" sublist, and then a recursive call is made to quicksort(less)
private ArrayList<Comparable> quickSort(ArrayList<Comparable> qList) {
ArrayList<Comparable> less = new ArrayList<Comparable>();
ArrayList<Comparable> greater = new ArrayList<Comparable>();
if (qList.size() <= 1)
return qList;
Comparable pivot = qList.get(qList.size() / 2);
for (int i = 0; i < qList.size(); i++) {
if ((qList.get(i).compareTo(pivot)) <= 0) {
comps++;
less.add(qList.get(i));
} else {
comps++;
greater.add(qList.get(i));
}
}
ArrayList<Comparable> toReturn = new ArrayList<Comparable>(
quickSort(less));
toReturn.add(pivot);
toReturn.addAll(quickSort(greater));
return toReturn;
}
If I just run the code with a list of size 20, I get this error
Exception in thread "main" java.lang.StackOverflowError
at java.util.Arrays.copyOf(Unknown Source)
at java.util.ArrayList.ensureCapacity(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at file.quickSort(CMSC351P1.thisClass:40)
at file.quickSort(CMSC351P1.thisClass:48)