[英]QuickSort Algorithm “StackOverFlowError”
我正在实现通过GeeksForGeeks提供的“ QuickSort”算法。 我正在对50K个随机数字的输入大小进行排序,我收到一条错误消息“ StackOverFlowError”。 这是递归调用不知道何时达到基本情况的情况吗? 崩溃发生在第58行。
int partition(int arr[], int low, int high)
{
int pivot = arr[high];
int i = (low-1); // index of smaller element
for (int j=low; j<high; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++;
// swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// swap arr[i+1] and arr[high] (or pivot)
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
/* The main function that implements QuickSort()
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void sort(int arr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[pi] is
now at right place */
int pi = partition(arr, low, high);
// Recursively sort elements before
// partition and after partition
sort(arr, low, pi-1); // Line 58, on my IDE
sort(arr, pi+1, high);
}
}
这是递归调用不知道何时达到基本情况的情况吗?
此方法适用于较小的数组。 如果没有达到基本情况,它将根本无法工作。 所以不行。
您用完了堆栈大小,因为每次进入递归时都会在内存中保留阵列的副本。
我看不到您的代码有任何问题。 它必须是堆栈大小,尝试使用增加它
将其设置为2 MB。
java -Xss2m QuickSort
如果您使用的是IDE,请在IntelliJ / Ecllipse的“运行配置”中进行更改/添加。
Java不会将数组保存在堆栈中。 而是将它们保存在堆中。 因此,您只需将引用复制到堆中的数组而不是数组。 当您将数组传递给方法时,可以通过引用传递它。 所以对你的问题。 我也有同样的问题。 而且,如果您增大堆栈大小,则抛出StackOverFlow所需的时间会更长。 因此,这不是解决方案。 如果找到它,则将其添加到此处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.