简体   繁体   English

Java中的堆栈溢出错误

[英]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. 我正在尝试编写一个程序,该程序使用递归和分区之类的快速排序来找到第k个最小的元素,从而不必对整个数组进行排序。 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 . 您的错误是j应该从0开始,而不是half+1 Currently, you're copying the portion of your array that is above the pivot into the top half of Right . 当前,您正在将数组中枢轴上方的部分复制到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. 如果您遵循递归的右侧,那么可以确保在该点之后,枢轴将永远保持等于0 ,因此您将永远不会停止递归。

Also, there are several other problems here: 另外,这里还有其他一些问题:

  • You're assuming that no element of A is equal to 0 , which is a dangerous assumption. 您假设A任何元素都不等于0 ,这是一个危险的假设。
  • You're using fixed int[200] 's. 您正在使用固定的int[200] This is Java; 这是Java; you can allocate these things at runtime. 您可以在运行时分配这些东西。 Just let Right and Left be sized appropriately based on n . 只需根据n适当调整RightLeft大小即可。 Right now your program will fail for every A of size 400 or larger. 现在,对于每A大于或等于400的A ,您的程序都会失败。

Surely 一定

if(k-1 == q)
   {

will never be true, as 永远不会是真的,因为

if(k > q)
   {

shields it. 屏蔽它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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