当数组中包含负数时,快速排序会引发堆栈溢出错误 (Dart)
我正在尝试在 dart 中实现快速排序,当我不包含负数时,下面的代码工作正常。但是,每当我在数组中包含负数时,就会出现堆栈溢出错误。如果有人能指出我做错了什么的正确方向,我会很高兴。
main() {
// The Partition Function
int partitionArray(List array, int lowerbound, int upperbound) {
int start = lowerbound;
int end = upperbound;
int pivotElement = array[lowerbound];
while (start < end) {
while (array[start] <= pivotElement) {
start++;
}
while (array[end] > pivotElement) {
end--;
}
// Swap the elements
if (start < end) {
int swapHolder;
swapHolder = array[start];
array[start] = array[end];
array[end] = swapHolder;
}
}
// Swap Pivot element and current element at end
int pivotSwapHolder;
pivotSwapHolder = array[lowerbound];
array[lowerbound] = array[end];
array[end] = pivotSwapHolder;
return end;
}
List arr = [ 7,5,6,3,7,-5,3,8,];
quickSortElements(List arr, int lower, int upper) {
if (lower < upper) {
int midLocation = partitionArray(arr, lower, arr.length - 1);
quickSortElements(arr, lower, midLocation - 1);
quickSortElements(arr, midLocation + 1, upper);
}
print(arr);
}
quickSortElements(arr, 0, arr.length - 1);
}
I am trying to implement quick sort in dart, The code below works fine When I do not include a negative number. However whenever I include a negative number in the array I get a stack overflow error. I'll be glad if anyone can point me in the right direction as to what I'm doing wrong.
main() {
// The Partition Function
int partitionArray(List array, int lowerbound, int upperbound) {
int start = lowerbound;
int end = upperbound;
int pivotElement = array[lowerbound];
while (start < end) {
while (array[start] <= pivotElement) {
start++;
}
while (array[end] > pivotElement) {
end--;
}
// Swap the elements
if (start < end) {
int swapHolder;
swapHolder = array[start];
array[start] = array[end];
array[end] = swapHolder;
}
}
// Swap Pivot element and current element at end
int pivotSwapHolder;
pivotSwapHolder = array[lowerbound];
array[lowerbound] = array[end];
array[end] = pivotSwapHolder;
return end;
}
List arr = [ 7,5,6,3,7,-5,3,8,];
quickSortElements(List arr, int lower, int upper) {
if (lower < upper) {
int midLocation = partitionArray(arr, lower, arr.length - 1);
quickSortElements(arr, lower, midLocation - 1);
quickSortElements(arr, midLocation + 1, upper);
}
print(arr);
}
quickSortElements(arr, 0, arr.length - 1);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的错误不是由于数组中的负值,它可能是任何低值,您会遇到相同的问题。您犯的错误是将
arr.length -1
作为递归调用中的上行值。请参阅下面,我评论已纠正的行:Your bug is not due to the negative value in the array, it could have been any low value and you would have the same problem. The mistake you did was to pass
arr.length - 1
as the upperbound value in your recursive call to quickSortElements. See below, I put in comment the line that has been corrected: