I have implemented a quicksort of an array of integers as follows:
public void Quicksort(int left, int right)
{
/* The recursive quicksort algorithm consists of four steps:
* 1. If there are one or less elements in the array to be sorted, return immediately.
* 2. Pick an element in the array to serve as a "pivot" point. (Usually the left-most element in the array is used.)
* 3. Split the array into two parts - one with elements larger than the pivot and the other with elements smaller than the pivot.
* 4. Recursively repeat the algorithm for both halves of the original array.
*/
int pivot = dataTable[left];
int l_hold = left;
int r_hold = right;
while (left < right)
{
while ((dataTable[right] >= pivot) && (left < right))
right--;
if (left != right)
{
dataTable[left] = dataTable[right];
left++;
}
while ((dataTable[left] <= pivot) && (left < right))
left++;
if (left != right)
{
dataTable[right] = dataTable[left];
right--;
}
}
dataTable[left] = pivot;
pivot = left;
left = l_hold;
right = r_hold;
if (left < pivot)
Quicksort(left, pivot - 1);
if (right > pivot)
Quicksort(pivot + 1, right);
}
It runs okay with an array of, say, 500 000 randomly generated integers. If I fill the array with ascending or descending integers, the quicksort causes a StackOverflowException at around 8800 elements.
I spy with my little eye no clear reason for this. Can you spy a reason with your huge amounts of pairs of eyes? I could go and just find a copypasta of functioning quicksort, but I'd rather find the reason as to what's causing the problem.
The method works on an array that's part of the class and is usually called with (index 0, last index - 1). Thousands of thanks in advance!