I am getting stackoverflow error when I am trying to sort using quicksort an array of large size, and this array is in descending order. I want to sort it in ascending order using the code below:
int partition_lastElementPivot(int * arr, int lo, int hi)
{
int x = arr[hi];
int i = lo - 1;
for (int j = lo; j < hi; j++)
{
if (arr[j] <= x)
{
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[hi];
arr[hi] = arr[i + 1];
arr[i + 1] = temp;
return i + 1;
}
void quicksortLastElementPivot(int*arr, int lo, int hi)
{
if (lo<hi)
{
int mid = partition_lastElementPivot(arr, lo, hi);
quicksortLastElementPivot(arr, lo, mid - 1);
quicksortLastElementPivot(arr, mid + 1, hi);
}
}
This code works fine when I randomly generate an array of any size, suppose of size 5000. But when I generate an array of size 5000 sorted in descending order and then try to sort using this code, I get a stackoverflow error. Does C++ limits the memory useable by stack and why is this happening.
int arr[5000];
int count = 5001;
for(int i=0; i<5000; i++)
{
arr[i] = count;
count--;
}
quicksortLastElementPivot(arr, 0, 4999)
Thanks