This is my quick sort algorithm implementation. I'm getting System.StackOverflowException
with the message 'Exception of type 'System.StackOverflowException' was thrown.' while trying to sort an array larger than 15k elements. I actually checked with 15000, 19000, 20000, 30000 elements, and the exception was thrown for the last 3 inputs.
private static int ArraySplitter(int[] intArr, int low, int high)
{
int pivot = intArr[high];
int lowIndex = (low - 1);
for (int i = low; i < high; i++)
{
if (intArr[i] <= pivot)
{
lowIndex++;
int temp = intArr[lowIndex];
intArr[lowIndex] = intArr[i];
intArr[i] = temp;
}
}
int tempHigh = intArr[lowIndex + 1];
intArr[lowIndex + 1] = intArr[high];
intArr[high] = tempHigh;
return lowIndex + 1;
}
private static void QSort(int[] intArr, int low, int high)
{
if (low < high)
{
int index = ArraySplitter(intArr, low, high);
QSort(intArr, low, index - 1);
QSort(intArr, index + 1, high);
}
}
public static void QuickSort(int[] intArr)
{
QSort(intArr, 0, intArr.Length - 1);
}
My python implementation also breaking for an array with larger than 5000 elements. Here is my python code -
def QUICKSORT(arr, p, r):
if p < r:
q = PARTITION(arr, p, r)
QUICKSORT(arr, p, q-1)
QUICKSORT(arr, q+1, r)
def PARTITION(arr, p, r):
x = arr[r]
i = p-1
for j in range(p, r-1):
if arr[j] <= x:
i = i + 1
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
temp = arr[i+1]
arr[i+1] = arr[r]
arr[r] = temp
return i+1
I followed the pseudocode from Thomas H Cormen's Introduction to algorithms.
What's seems to be the problem and how to fix this issue?