[英]C++ QuickSort implementation that sorts everything but a single element
這是我第一次寫 C++。 我正在嘗試參考麻省理工學院公開課件幻燈片(特別是幻燈片 4 和 17)來實現 QuickSort。
但是,有一個錯誤:
input: 6 10 13 5 8 3 2 11
output: 2 5 3 6 8 11 10 13
我不確定為什么5
不合適。 我的代碼似乎完美地反映了幻燈片。
#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;
}
幻燈片上說for j ← p + 1 to q
,你轉向for (int j = p+1; j < q; j++)
。 這是一個逐一錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.