gpt4 book ai didi

Java堆栈溢出与递归

转载 作者:行者123 更新时间:2023-12-01 14:02:34 25 4
gpt4 key购买 nike

所以我正在编写一个程序,它将使用快速排序对自定义字符串数组列表进行排序。 (我必须自定义编写一个类的所有代码)。但是,我不断收到堆栈溢出错误,但我不知道为什么。 (我是初学者,所以放轻松)。

void quickSort () {
recursiveQuickSort(0, numElements-1);
}
// Recursive quicksort
public void recursiveQuickSort(int start, int end) {
// if size 1 or less, don't need to do anything
int pivotPosition = 0;
if (start <=1 || end <= 1 ) {

} else
pivotPosition =partition(start, end);
recursiveQuickSort(start, pivotPosition-1);
recursiveQuickSort(pivotPosition+1, end);
}
static int partition(int start, int end) {
int pivot = end;
end--;
while(true) {
while (true) {
if (end < start) {
break;
}
if (end < pivot) {
end = end;
break;
} else end --;
}
while(true) {
if (end < start) {
break;
}
if (start > pivot) {
start = start;
break;
} else start++;
}
if(end < start) {
break;
}
else
swap(start, end);
}
swap(end+1, pivot);
return end + 1;
}

最佳答案

递归快速排序中,您在else上缺少大括号,因此递归调用是无条件执行的。

添加大括号来解决此问题:

public void recursiveQuickSort(int start, int end) {
// if size 1 or less, don't need to do anything
int pivotPosition = 0;
if (start <=1 || end <= 1 ) {

} else { // <<== Here
pivotPosition =partition(start, end);
recursiveQuickSort(start, pivotPosition-1);
recursiveQuickSort(pivotPosition+1, end);
} // <<== Here
}

关于Java堆栈溢出与递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19238219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com