简体   繁体   中英

Stack Overflow Error in Java

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;

Your error is that j should start at 0 , not at half+1 . Currently, you're copying the portion of your array that is above the pivot into the top half of Right . If you ever follow the right side of the recursion, you're guaranteed that the pivot will forever remain equal to 0 after that point, so you'll never stop recursing.

Also, there are several other problems here:

  • You're assuming that no element of A is equal to 0 , which is a dangerous assumption.
  • You're using fixed int[200] 's. This is Java; you can allocate these things at runtime. Just let Right and Left be sized appropriately based on n . Right now your program will fail for every A of size 400 or larger.

Surely

if(k-1 == q)
   {

will never be true, as

if(k > q)
   {

shields it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM