- #1
Enharmonics
- 29
- 2
I have to sort an array in increasing order based on the compareTo method. I'm not allowed to use the Arrays, Collections, Set, or Map classes.
Here's my code:
The trouble is, I'm getting a StackOverflow error at the line
And then a whole bunch of them at the line
The fact that I'm getting a bunch of repeated errors at the recursive call line tells me it might be an infinite recursion problem, but I just can't see why.
I also don't know why it's throwing an error at the compareTo line... based on how the method works, it seems like the logic is right? Don't know if it matters, but the array I'm using in my driver to test my QuickSort code is:
Any help with this would be appreciated. I'm kinda stumped.
Here's my code:
Java:
public static <T extends Comparable<? super T>>
void sort (T[] arr)
{
// If arr is null, empty,
// or only has 1 element,
// it is already sorted
if (arr == null || arr.length == 0
|| arr.length == 1)
return;
// Call overloaded sort method
sort(arr, 0, arr.length - 1);
}
// OVERLOADED SORT METHOD
public static <T extends Comparable<? super T>>
void sort(T[] arr, int left, int right)
{
// To be used while sorting
int i = left;
int j = right;
// Check if left and
// right indices are out
// of order. If they are,
// nothing can be done
if (right <= left)
return;
// Middle element used
// as pivot
T pivot = arr[(left + (right - left)) / 2];
// temp will be used
// to swap elements later
T temp;
// QuickSort algorithm
while (i <= j)
{
// Look for values on
// the left greater than
// the pivot and values
// on the right smaller
// than the pivot
// When you find both, swap them
while (arr[i].compareTo(pivot) < 0)
{
i++;
}
while (arr[j].compareTo(pivot) > 0)
{
j--;
}
// Check that i hasn't
// passed j already
if (i <= j)
{
// Swap the items
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
// Move both indices
// to their next position
i++;
j--;
}
}
// Recursive calls to the
// sort method
if (left < j)
sort(arr, left, j);
if (i < right)
sort(arr, i, right);
}
The trouble is, I'm getting a StackOverflow error at the line
Java:
while (arr[i].compareTo(pivot) < 0)
And then a whole bunch of them at the line
Java:
sort(arr, i, right);
The fact that I'm getting a bunch of repeated errors at the recursive call line tells me it might be an infinite recursion problem, but I just can't see why.
I also don't know why it's throwing an error at the compareTo line... based on how the method works, it seems like the logic is right? Don't know if it matters, but the array I'm using in my driver to test my QuickSort code is:
Java:
String[] wordArray = {"Droplet", "Blueberry", "Elephant",
"Fate", "Apple", "Coconut", "Darjeeling"};
Any help with this would be appreciated. I'm kinda stumped.