I'm trying to code a program that finds the kth smallest element using recursion and quick sort like partitioning so as not to have to sort the entire array. I feel like my code should work, but I get a stack overflow error immediately when the function is called so I can't test it.
I thought stack overflow had to do with overflowing the execution stack, and I understand it happens with recursion, but the error gets called on the very first line of the function so it's confused me. If someone could take a look at this and give some suggestions I would really appreciate it. Thanks.
public static int find_kth_smallest( int[] A, int n, int k )
{
int[] Left = new int[200];
int[] Right = new int[200];
int half = n/2;
int x = 0; int j = half + 1; int q = 0;
int count = 0;
int pivot = A[half];
for(int i = 0; i < n; i++)
{
if(A[i] < pivot)
{
Left[x] = A[i];
x++;
}
if(A[i] > pivot)
{
Right[j] = A[i];
j++;
}
}
while(Left[q] != 0)
q++;
if(k < q)
{
return find_kth_smallest(Left, q, k);
}
if(k > q)
{
return find_kth_smallest(Right, n-q, k);
}
if(k-1 == q)
{
return A[pivot];
}
return -1;