【发布时间】:2016-02-21 00:42:13
【问题描述】:
您好,我正在尝试在 Java 中实现 Quicksort 方法,但由于某种原因,当我只执行 5 个元素时,我遇到了堆栈溢出错误!有什么想法可能是错的吗? 我的部分代码:
class QuickSort implements AbstractSort {
public int partition(int[] numbers, int start, int end)
{
int pivot = numbers[end];
int theIndex = start;
int temp;
for(int i = start; i <= end - 1; i++)
{
if(numbers[i] <= pivot)
{
temp = numbers[theIndex];
numbers[theIndex] = numbers[i];
numbers[i] = temp;
theIndex++;
}
}
temp = numbers[theIndex];
numbers[theIndex] = pivot;
numbers[end] = temp;
return theIndex;
}
public void mySort(int[] numbers, int start, int end)
{
if(start < end)
{
int myIndex = partition(numbers, start, end);
mySort(numbers, 0, myIndex-1);
mySort(numbers, myIndex + 1, numbers.length - 1);
}
else
{
return;
}
}
public void sort(int[] numbers)
{
mySort(numbers, 0, numbers.length - 1);
}
}
【问题讨论】:
-
你能提供一些你正在尝试排序的例子吗?
-
我使用了 9 0 8 5 6 ...但我已经找到了问题所在!我不应该在我的递归快速排序中传递 0,而是“开始”。所以代替 mySort(numbers, 0, myIndex-1);它应该是 mySort(numbers, start, myIndex-1);
标签: java algorithm recursion stack-overflow quicksort