我编写了一个小的 Java 程序来实现 int 数组的冒泡排序技术。它适用于 1000 个单位的数组,但是当我将它增加到 10000 个时,它会因 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);
}
}
}
}
非常感谢任何帮助!
最佳答案
撇开逻辑不谈,它在 10000
时失败的技术原因是因为 Java 中的每个线程都有一个固定的堆栈大小。当您使用 10000 时,它无法找到足够的内存。
使用 -XX:ThreadStackSize=512
增加 JVM 分配给线程的默认内存,它可能会起作用。但通常您不必为此操心。
在旁注中检查您是否真的需要递归。
关于使用大型数组的冒泡排序时,Java 程序因 StackOverflow 而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21769552/