1.快速排序
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int a[N], n;
void quickSort(int l, int r){
int key = a[(l + r) / 2], i = l, j = r;
while (i < j){
while (a[i] < key)
i++;
while (a[j] > key)
j--;
if (i <= j)
swap(a[i++], a[j--]);
}
if (l < j) quickSort(l, j);
if (i < r) quickSort(i, r);
}
int main(){
cin >> n;
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
quickSort(1, n);
for (int i = 1; i <= n; i++)
cout << a[i] << " \n"[i == n];
return 0;
}
洛谷模板:https://www.luogu.com.cn/problem/P1177
Acwing模板:https://www.acwing.com/problem/content/787/
2.歸并排序
#include <bits/stdc++.h>
using namespace std;
#define LL long long
const int N = 1e5 + 10;
LL a[N], tmp[N], n;
void mergeSort(LL l, LL r){
if (l >= r) return;
LL mid = (l + r) >> 1, i = l, j = mid + 1, cnt = 0;
mergeSort(l, mid);
mergeSort(mid + 1, r);
while (i <= mid || j <= r)
if (j > r || (i <= mid && a[i] <= a[j]))
tmp[cnt++] = a[i++];
else
tmp[cnt++] = a[j++];
for (LL k = 0; k < r - l + 1; k++)
a[l + k] = tmp[k];
}
int main(){
cin >> n;
for (int i = 1; i <= n; i++)
scanf("%lld", &a[i]);
mergeSort(1, n);
for (int i = 1; i <= n; i++)
cout << a[i] << " \n"[i == n];
return 0;
}
應(yīng)用:
求解逆序?qū)?/strong>
https://www.luogu.com.cn/problem/P1908 題解:http://www.rzrgm.cn/Hamine/p/15689892.html
https://codeforces.com/contest/1591/problem/D 題解:http://www.rzrgm.cn/Hamine/p/15689988.html
作者:Hamine
本文版權(quán)歸作者和博客園共有,歡迎轉(zhuǎn)載,但必須給出原文鏈接,并保留此段聲明,否則保留追究法律責(zé)任的權(quán)利。
浙公網(wǎng)安備 33010602011771號(hào)