【问题标题】:Java program crashes with StackOverflow when using bubble sort of a large array使用大数组的冒泡排序时,Java 程序因 StackOverflow 崩溃
【发布时间】:2014-02-14 02:09:36
【问题描述】:

我编写了一个小型 Java 程序,为 int 数组实现冒泡排序技术。它适用于 1000 个单位的数组,但是当我将其增加到 10 000 个时,它会因 java.lang.StackOverflowError 而崩溃。

代码如下:

import java.util.*;
import java.lang.*;

class BubbleSort
{
  public static void main (String [] argv)
  {
    int Array [] = new int [10000];
    for (int a = 0; a < 10001; a++)
    {
    Array[a] = (int) (Math.random()*100);
    }  
    // generated an array of 10000 units and filled with random numbers

    for (int end = Array.length-1; end >= 0; end--)
    {
      BubbleSort (Array, 0, end);
    }

  }


  public static int BubbleSort (int A [], int count, int end)
  {

    if (count == end) //debugger says crash occurs here
    {
      return count;
    }

    else
    {

       if (A[count] > A[count+1])
       {
         int temp = A[count];
         A[count] = A[count+1];
         A[count+1] = temp;

         return BubbleSort(A, count+1, end); //and here

       }

     else
     {
        return BubbleSort(A, count+1, end);
     }
  } 

 }
}

非常感谢任何帮助!

【问题讨论】:

  • 你为什么使用递归?你确定a &lt; 10001 看起来会先崩溃吗?请遵循 Java 大小写约定。
  • 小心在 Java 中使用递归:programmers.stackexchange.com/questions/194646/…
  • @ecbrodie 仅仅存在堆栈溢出和/或缺乏尾递归优化并不是在 Java 或任何其他语言中避免递归的理由。
  • @ElliottFrisch 错字,对不起,它本来是一个

标签: java arrays stack-overflow bubble-sort


【解决方案1】:

撇开逻辑不谈,它在10000 失败的技术原因是因为Java 中的每个线程都有一个固定堆栈大小。而当你使用 10000 时,它无法找到足够的内存。

使用-XX:ThreadStackSize=512 增加JVM 分配给线程的默认内存,它可能会起作用。但一般来说你不必为此烦恼。

在旁注中检查您是否真的需要在这里递归。

【讨论】:

  • 如果我不使用递归(正如您正确指出的,我不需要它,但我想练习这样做),我不需要增加固定堆栈大小?
  • 是的,你是对的。对于正常的应用程序来说已经足够了。只有当您有这样的特殊要求时,才需要更改。
猜你喜欢
  • 2013-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-17
  • 2016-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多