Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

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;
} 
share|improve this question

marked as duplicate by Raedwald, CT Zhu, Divi, tmyklebu, Pranav Singh Jun 26 '14 at 2:51

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer 1

up vote 1 down vote accepted

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
}
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.