[英]There's a memory access exception but I'm not sure what's wrong in my code
我正在 Visual Studio 中测试一些快速排序的案例,但我得到了错误,我不确定我的代码有什么问题。
这是我的代码。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void Swap(int *arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
void BubbleSort(int *arr, int len) {
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
Swap(arr, j, j + 1);
}
}
}
}
void QuickSort(int *arr, int left, int right) {
if (left >= right) {
return;
}
int pivot = arr[left];
int low = left;
int high = right + 1;
while (low <= high) {
while (arr[++low] <= pivot && low <= right);
while (arr[--high] >= pivot && high > left);
if (low > high) {
Swap(arr, left, high);
}
else {
Swap(arr, low, high);
}
}
QuickSort(arr, left, high - 1);
QuickSort(arr, high + 1, right);
}
int main() {
srand((unsigned)time(NULL));
int *arr = new int[10000];
for (int i = 0; i < 10000; i++) {
arr[i] = rand() % 10000;
}
BubbleSort(arr, 10000);
QuickSort(arr, 0, 9999);
delete[] arr;
return 0;
}
如果我分配很小的内存并不重要,但是此代码的案例在我的 QuickSort() 函数中出现错误。
当pivot
是最大元素时,第一个内部while
循环将运行直到++low
is > right
,从而导致数组越界访问。 您必须在访问arr[++low]
之前检查low < right
。 同样的事情适用于第二个循环。
此外,使用std::swap
而不是滚动你自己的,使用std::size_t
作为数组索引,以及 C++ <random>
库而不是 C rand()
函数。 并且不要using namespace std
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.