I have a quick sort class that works on smaller list sizes but continuously gets SO errors on larger sizes even though I have a base case. I have a quick sort class that looks like this:
public class QuickSorter extends Sorter
{
@Override
public void sort(WordList toSort, Comparator<String> comp) throws NullPointerException{
// TODO
int front = 0;
int back = toSort.length() -1;
quickSortRec(toSort, comp, front, back);
}
private void quickSortRec(WordList list, Comparator<String> comp, int start, int end){
// TODO
if (start >= end) {
return;
}
int pivotPoint = partition(list, comp, start, end);
quickSortRec(list, comp, start, pivotPoint - 1);
quickSortRec(list, comp, pivotPoint + 1, end);
}
private int partition(WordList list, Comparator<String> comp, int start, int end){
// TODO
String pivotSpot = list.get(end);
int pivotIndex = start;
for(int i = start; i < end; i++) {
if(comp.compare(list.get(i), pivotSpot) < 0) {
list.swap(i, pivotIndex);
}
}
list.swap(end, pivotIndex);
return pivotIndex;
}
}
My code works just fine on smaller lists that I need to sort but I get a repeating StackOverflow exception on line 36
Stack trace looks like this:
Exception in thread "main" java.lang.StackOverflowError
at hw2.AlphabetComparator.compare(AlphabetComparator.java:1)
at hw2.Sorter$CountingComparator.compare(Sorter.java:272)
at hw2.QuickSorter.partition(QuickSorter.java:53)
at hw2.QuickSorter.quickSortRec(QuickSorter.java:32)
at hw2.QuickSorter.quickSortRec(QuickSorter.java:36)
at hw2.QuickSorter.quickSortRec(QuickSorter.java:36)
at hw2.QuickSorter.quickSortRec(QuickSorter.java:36)
at hw2.QuickSorter.quickSortRec(QuickSorter.java:36)
AlphabetComparator:
int length = b.length(); // holds smallest length of both strings so I don't get an out of bounds exception with my for loop
if (a.length() < b.length()) // default length will be String b's length if b is less than a or a and b are ==
{
length = a.length();
}
for (int i = 0; i < length; i++)
{
if (a.charAt(i) != b.charAt(i)) // if character at same index in both strings aren't equal
{
if (alphabet.isValid(a.charAt(i)) == true && alphabet.isValid(b.charAt(i)) == true) // if both characters are valid in the alphabet
{
return alphabet.getPosition(a.charAt(i)) - alphabet.getPosition(b.charAt(i)); // return negative or positive
}
}
}
if (a.length() != b.length())
{
if (length == a.length())
{
return -1;
} else
return 1;
}
return 0;
}
```