简体   繁体   English

Quicksort中的StackOverflow

[英]StackOverflow in Quicksort

I'm getting a Stackoverflow if I try this code with numbers.length n = 100.000 ("." just for readability) and numbers being in inverse order so like 100.000 99.999 99.998 ... Is that normal? 如果我尝试使用Numbers.length n = 100.000(“。”仅出于可读性)且这段代码是相反的顺序(例如100.000 99.999 99.998),那我就会得到Stackoverflow ...这正常吗? It works for smaller n like 10.000. 它适用于较小的n,例如10.000。

private void quickSort(int[] numbers, int l, int r) {
    if (l < r) {
      int p = numbers[r];
      int i = l - 1;
      int j = r;
      do {
        do {
          i++;
        } while (numbers[i] < p);
        do {
          j--;
        } while (j >= l && numbers[j] > p);
        if (i < j) {
          swap(numbers, i, j);
        }
      } while (i < j);
      swap(numbers, i, r);
      quickSort(numbers, l, i - 1);
      quickSort(numbers, i + 1, r);
    }
  }

You are probably making too many recursive calls, because the array is already sorted. 您可能进行了太多的递归调用,因为该数组已经排序。 You can allow JVM to use up more memory or change the maximum recursive depth. 您可以允许JVM使用更多的内存或更改最大递归深度。 A better solution is to implement a non-recursive quicksort. 更好的解决方案是实现非递归快速排序。 Here's a Java example . 这是一个Java 示例

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

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