0

so i'm writing a program that will sort a custom arrayList of strings using quicksort. (I have to custom write all the code for a class). However, I keep getting a stack overflow error and I don't know why. (I'm a beginner so take it easy).

void quickSort () {
    recursiveQuickSort(0, numElements-1);
}
// Recursive quicksort
public void recursiveQuickSort(int start, int end) {
    // if size 1 or less, don't need to do anything
    int pivotPosition = 0;
    if (start <=1 || end <= 1 ) {

    } else 
        pivotPosition =partition(start, end);
        recursiveQuickSort(start, pivotPosition-1);
        recursiveQuickSort(pivotPosition+1, end);
}
static int partition(int start, int end) {
    int pivot = end;
    end--;
    while(true) {
        while (true) {
            if (end < start) {
                break;
            }
            if (end < pivot) {
                end = end;
                break;
            } else end --;
        }
        while(true) {
            if (end < start) {
                break;
            }
            if (start > pivot) {
                start = start;
                break;
            } else start++;
        }
        if(end < start) {
            break;
        }
        else
            swap(start, end);
    }
             swap(end+1, pivot);
     return end + 1;
} 
tshepang
  • 12,111
  • 21
  • 91
  • 136

1 Answers1

1

You are missing curly braces on the else in recursiveQuickSort, so recursive calls are performed unconditionally.

Add curly braces to fix this:

public void recursiveQuickSort(int start, int end) {
    // if size 1 or less, don't need to do anything
    int pivotPosition = 0;
    if (start <=1 || end <= 1 ) {

    } else { // <<== Here
        pivotPosition =partition(start, end);
        recursiveQuickSort(start, pivotPosition-1);
        recursiveQuickSort(pivotPosition+1, end);
    }        // <<== Here
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523