I'm trying to implement the quick sort algorithm, where i choose the pivot to be the rightmost element.. However, when the array of ~4000 elements already is sorted, stack overflow occurs. This is my implementation: 

```
void quickSortSimpleAscending(int elements[], int startindex, int endindex)
{

    int pivot = elements[endindex];
    int i = startindex;
    int j = endindex;

    while (i < j)
    {

        while (elements[i] < pivot)
            i++;

        while (elements[j] > pivot)
            j--;

        if (i <= j)
        {
            swap(elements[i], elements[j]);
            i++;
            j--;
        }
    }

    if (startindex < j)
        quickSortSimpleAscending(elements, startindex, j);

    if (i < endindex)
        quickSortSimpleAscending(elements, i, endindex);
}

```

Is there any way to solve this without using the method "median of three"? 
Thanks!