目录
一·快排(不稳定):分治
传统快排(nlogn)
1.找到分界点
2.>=x(partition)放左,<=x放右(两指针越过时停止),partition每次随机或取中值比取边界要快
3.递归
注意:模板涉及很多边界问题,x, i,j及符号不能随意更改,牵一发而动全身。
#include<algorithm>
#include<iostream>
using namespace std;
const int N = 1e6 + 10;
int n;
int q[N];
void quick_sort(int q[], int l, int r)
{
if (l >= r)//一个数或没有数return
return;
int x = q[(l+r)/2], i = l - 1, j = r + 1;
while (i<j)
{
do i++; while (q[i] < x);
do j--; while (q[j] > x);
if (i < j) swap(q[i], q[j]);
}
quick_sort(q, l, j);
quick_sort(q, j + 1, r);
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &q[i]);
}
quick_sort(q, 0, n-1);
for (int i = 0; i < n; i++)
{
printf("%d ", q[i]);
}
return 0;
}
快速选择求第k个数(O(n))
k<=sl,递归左边,否则递归右边
#include<iostream>
#include<algorithm>
using namespace std;
int n, k;
const int N = 1e6;
int q[N];
int quick_sort( int l, int r,int k)
{
if (l == r) return q[l]; // 只有一个数时就是所求,永远保证第k个数在所求区间
int x = q[(l + r ) /2], i = l - 1, j = r + 1;
while (i < j)
{
do i++; while (q[i] < x);
do j--; while (q[j] > x);
if (i < j) swap(q[i], q[j]);
}
int sl = j - l + 1;//l到j所有数
if (k <= sl)
return quick_sort(l, j, k);
else
return quick_sort(j + 1, r, k-sl);
}
int main()
{
cin >> n >> k;
for (int i = 0; i < n; i++)
{
cin >> q[i];
}
cout << quick_sort(0, n - 1, k) << endl;
return 0;
}
二·归并(稳定,O(nlogn)):
传统归并
1.确定分界点(数组中间位置)
2.递归排序left,right
3。归并合二为一
#include<algorithm>
#include<iostream>
using namespace std;
const int N = 1e6+10;
int n;
int q[N],tmp[N];
void merge_sort(int q[], int l, int r)
{
if (l >= r) return;
int mid = l + r >>1;
merge_sort(q, l, mid);
merge_sort(q, mid + 1, r);
int k = 0,i = l, j = mid + 1;
while (i <= mid && j <= r)
{
if (q[i] <= q[j]) tmp[k++] = q[i++];
else tmp[k++] = q[j++];
}
while(i<=mid) tmp[k++] = q[i++];
while(j<=r) tmp[k++] = q[j++];
for (int i = l, j = 0; i <= r; i++, j++) q[i] = tmp[j];
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &q[i]);
}
merge_sort(q, 0, n-1);
for (int i = 0; i < n; i++)
{
printf("%d ", q[i]);
}
return 0;
}
求逆序对数量
给定一个长度为 n 的整数数列,请你计算数列中的逆序对的数量。
逆序对的定义如下:对于数列的第 i个和第 j个元素,如果满足 i<j 且 a[i]>a[j],则其为一个逆序对;否则不是。
左半边逆序对数量 merge_sort(l,mid)
右半边逆序对数量 merge_sort(mid+1,r)
被分界点隔开的逆序对数量 mid-i+1(i:左 j:右 i前所有数满足小于j,i及i后所有数满足大于j)
#include<algorithm>
#include<iostream>
using namespace std;
typedef long long LL;
const int N = 1e6+10;
int n;
int q[N],tmp[N];
LL merge_sort(int l, int r)
{
if (l >= r) return 0;
int mid = l + r >> 1;
LL res = merge_sort(l, mid) + merge_sort(mid + 1, r);
int k = 0, i = l, j = mid + 1;
while (i <= mid && j <= r)
{
if (q[i] <= q[j]) tmp[k++] = q[i++];
else {
res += mid - i + 1;//q[i]>q[j],并且q[i]后所有数都能和q[j]组成对
tmp[k++] = q[j++];
}
}
while (i <= mid) tmp[k++] = q[i++];
while (j <= r) tmp[k++] = q[j++];
for (int i = l, k = 0; i <= r; i++, k++)
q[i] = tmp[k];
return res;
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &q[i]);
}
cout << merge_sort(0, n - 1);
return 0;
}