[英]C++ QuickSort implementation that sorts everything but a single element
This is my first time writing C++.这是我第一次写 C++。 I am trying to implement QuickSort referencing the MIT open course ware slides (Slides 4 and 17 specifically).我正在尝试参考麻省理工学院公开课件幻灯片(特别是幻灯片 4 和 17)来实现 QuickSort。
However, there is a bug:但是,有一个错误:
input: 6 10 13 5 8 3 2 11
output: 2 5 3 6 8 11 10 13
I'm not sure why the 5
is out of place.我不确定为什么5
不合适。 My code seems to mirror the slides perfectly.我的代码似乎完美地反映了幻灯片。
#include <utility>
using namespace std;
template <typename T>
void print_array(T &arr) {
for (int i : arr) {
cout << i << " ";
}
cout << endl;
}
int partition(int* a, int p, int q) {
int x = a[p];
int i = p;
for (int j = p+1; j < q; j++) {
if (a[j] <= x) {
i++;
swap(a[i], a[j]);
}
}
swap(a[p], a[i]);
return i;
}
void quicksort(int* a, int p, int r) {
if (p < r) {
int q = partition(a, p, r);
quicksort(a, p, q-1);
quicksort(a, q+1, r);
}
}
int main() {
int keys[8] = {6, 10, 13, 5, 8, 3, 2, 11};
print_array(keys);
quicksort(keys, 0, 8);
print_array(keys);
return 0;
}
The slide says for j ← p + 1 to q
, which you turned to for (int j = p+1; j < q; j++)
.幻灯片上说for j ← p + 1 to q
,你转向for (int j = p+1; j < q; j++)
。 This is an off-by-one error.这是一个逐一错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.