【发布时间】: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 < 10001看起来会先崩溃吗?请遵循 Java 大小写约定。 -
小心在 Java 中使用递归:programmers.stackexchange.com/questions/194646/…
-
@ecbrodie 仅仅存在堆栈溢出和/或缺乏尾递归优化并不是在 Java 或任何其他语言中避免递归的理由。
-
@ElliottFrisch 错字,对不起,它本来是一个
标签: java arrays stack-overflow bubble-sort