c++生成快速排序代码
时间: 2023-10-12 14:01:03 浏览: 105
C++实现快速排序
根据引用的代码,你可以生成一个C++的快速排序。下面是一个示例:
```
#include <iostream>
#include <vector>
using namespace std;
int quick_partition(vector<int>& a, int p, int q) {
int i = p;
int x = a[p];
for (int j = p + 1; j <= q; j++) {
if (a[j <= x) {
i++;
swap(a[i], a[j]);
}
}
swap(a[i], a[p]);
return i;
}
void qsort(vector<int>& a, int p, int q) {
if (p < q) {
int k = rand() % (q - p + 1) + p;
swap(a[k], a[p]);
int mid = quick_partition(a, p, q);
qsort(a, p, mid - 1);
qsort(a, mid + 1, q);
}
}
int main() {
int n;
while (cin >> n) {
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
qsort(a, 0, n - 1);
for (int i = 0; i < n; i++) {
cout << a[i << " ";
}
cout << endl;
}
return 0;
}
```
此代码实现了一个快速排序算法,通过调用`qsort`函数可以对输入的一维整型数组进行排序。每次选择一个随机的主元元素来进行分区,将小于主元的元素放在左边,大于主元的元素放在右边,然后对左右两部分进行递归快速排序,最终达到升序排列的效果。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [C++ 随机化快速排序 最简单易懂的代码! 基于归并分区思想实现](https://blog.csdn.net/weixin_42429718/article/details/88830738)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *3* [C++:快速排序法的代码实现](https://blog.csdn.net/sweetorange_/article/details/111400263)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文