题面:
给定你一个长度为 的整数数列。
请你使用快速排序对这个数列按照从小到大进行排序。
并将排好序的数列按顺序输出。
原题链接:785. 快速排序 - AcWing
需要注意的几个点:
- 左右哨兵的发动顺序;
- 相同元素的相对位置;
- 边界划分问题。
| #include<bits/stdc++.h> |
| using namespace std; |
| |
| const int N = 100005; |
| |
| int n; |
| int a[N]; |
| |
| |
| void quickSort(int l, int r) { |
| |
| if (l > r) |
| return; |
| int tmp = a[l]; |
| int i = l; |
| int j = r; |
| while (i != j) { |
| |
| |
| |
| while (a[j] >= tmp && i < j) |
| j--; |
| |
| |
| |
| while (a[i] <= tmp && i < j) |
| i++; |
| |
| if (i < j) |
| swap(a[i], a[j]); |
| } |
| |
| a[l] = a[i]; |
| a[i] = tmp; |
| |
| quickSort(l, i - 1); |
| quickSort(i + 1, r); |
| } |
| |
| void quickSort2(int l, int r) { |
| if (l >= r) |
| return; |
| |
| int tmp = a[(l + r) >> 1]; |
| int i = l; |
| int j = r; |
| while (i <= j) { |
| |
| while (a[j] > tmp) |
| j--; |
| |
| while (a[i] < tmp) |
| i++; |
| |
| |
| |
| if (i <= j) |
| swap(a[i++], a[j--]); |
| } |
| quickSort2(l, j); |
| quickSort2(i, r); |
| } |
| |
| int main() |
| { |
| cin >> n; |
| for (int i = 0; i < n; i++) |
| cin >> a[i]; |
| |
| quickSort2(0, n - 1); |
| for (int i = 0; i < n; i++) |
| cout << a[i] << " "; |
| return 0; |
| } |
| |
| void quick_sort(int l, int r) |
| { |
| if(l==r) |
| return q[l]; |
| LL x=q[(l+r)>>1]; |
| int i=l-1; |
| int j=r+1; |
| while(i<j){ |
| |
| |
| while(q[++i]<x); |
| while(q[--j]>x); |
| if(i<j) |
| swap(q[i],q[j]); |
| } |
| quick_sort(l, j); |
| quick_sort(j+1, r); |
| } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· DeepSeek “源神”启动!「GitHub 热点速览」
· 上周热点回顾(2.17-2.23)