My QuickSort implementation causes StackOverflow error if I give reverse-sorted array. It is working fine for about 1000 items, but for 10000+ I get StackOverflow error. If I get the error the recursion depth is about 9000. I know my algorithm always choose the latest element of the subarray as pivot, which is not optimal, but I would not change that, because I want to make it work like this. Here is the code:
private int partition(int[] numbers, int begin, int end) {
    int pivot = numbers[end];
    int partitionIndex = begin;
    for (int i = begin; i < end; ++i) {
        comparisonCounter++;
        if (numbers[i] <= pivot) {
            if (i != partitionIndex) {
                swapCounter++;
                int temp = numbers[i];
                numbers[i] = numbers[partitionIndex];
                numbers[partitionIndex] = temp;
            }
            partitionIndex++;
        }
    }
    if (partitionIndex != end) {
        swapCounter++;
        int temp = numbers[partitionIndex];
        numbers[partitionIndex] = numbers[end];
        numbers[end] = temp;
    }
    return partitionIndex;
}
private void quickSort(int[] numbers, int begin, int end) {
    if (begin < end) {
        int partitionIndex = partition(numbers, begin, end);
        quickSort(numbers, begin, partitionIndex - 1);
        quickSort(numbers, partitionIndex + 1, end);
    }
}
Is there something wrong with my implementation? How could I fix it? Thank you!
 
     
     
    