[英]There's a memory access exception but I'm not sure what's wrong in my code
I'm testing some case of quick sort in visual studio but I got and error and I'm not sure what's wrong with my code.我正在 Visual Studio 中测试一些快速排序的案例,但我得到了错误,我不确定我的代码有什么问题。
Here's my code.这是我的代码。
#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;
}
It doesn't matter if I allocate little size of memory but this code's case got an error with my QuickSort() function.如果我分配很小的内存并不重要,但是此代码的案例在我的 QuickSort() 函数中出现错误。
When the pivot
is the largest element, the first inner while
loop will run until ++low
is > right
, causing an array out of bounds access.当
pivot
是最大元素时,第一个内部while
循环将运行直到++low
is > right
,从而导致数组越界访问。 You have to check low < right
before accessing arr[++low]
.您必须在访问
arr[++low]
之前检查low < right
。 Same thing applies for the 2nd loop.同样的事情适用于第二个循环。
Also, use std::swap
instead of rolling your own, use std::size_t
for array indices, and the C++ <random>
library instead of the C rand()
function.此外,使用
std::swap
而不是滚动你自己的,使用std::size_t
作为数组索引,以及 C++ <random>
库而不是 C rand()
函数。 And don't do using namespace std
.并且不要
using namespace std
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.