为什么我的快速排序溢出
Why is my QuickSort overflowing?
我正在尝试使用随机枢轴实现QuickSort()
当我不随机化枢轴,并选择它为A[0]时,一切都很好,但当我实现随机化时,事情就变得疯狂了。
分区:
int Partition(int A[], int left, int right, int pivot = 0)
{
swap(A[left], A[pivot]);
int temp = right;
while (pivot != temp)
{
// make a swap if needed
if (A[pivot] > A[temp] && temp > pivot || A[temp] > A[pivot] && temp < pivot)
{
// swap both data and index
swap(A[pivot], A[temp]);
swap(pivot, temp);
}
// advance the temp towards pivot
if (temp < pivot)
temp++;
else
temp--;
}
return pivot;
}
快速排序:
void QuickSort(int A[], int left, int right)
{
int pivot;
if (left < right) {
// randomize pivot
srand(time(NULL));
pivot = rand() % (right - left + 1);
// partition and call quicksort
pivot = Partition(A, left, right, pivot);
QuickSort(A, left, pivot - 1);
QuickSort(A, pivot + 1, right);
}
}
这里有一个问题:
pivot = rand() % (right - left + 1);
需要
pivot = left + rand() % (right - left + 1);
相关文章:
- 如何修复我的快速排序实现?
- C++运行时错误与快速排序算法抛出堆栈转储错误
- 在 MIPS 中快速排序
- 不正确的比较和交换计数器输出用于快速排序功能
- 使用 std::vector C++快速排序,EXC_BAD_ACCESS代码 2
- 使用快速排序对 C++ 中的可视化工具错误进行排序
- 快速排序 - 三个中位数枢轴选择 - 某些元素顺序不正确
- 并行快速排序分区中的隔离错误
- 实现 3 路分区以实现快速排序
- 为什么这个快速排序实现给出了一个奇怪的输出
- 我的快速排序在对预排序的项目进行排序时失败,如何改进?
- 快速排序不适用于大型数组
- 快速排序;分段错误,但找不到位置?
- 快速排序函数在快速排序算法中如何工作?
- 快速排序导致堆栈溢出
- C 快速排序给我堆栈溢出
- 为什么我的快速排序溢出
- 递归快速排序导致分段错误(不是溢出)
- 快速排序-最坏的情况会导致堆栈溢出
- 如何避免快速排序堆栈溢出