一. 快排模板
- 以j为分割点的模板
#include<iostream>
using namespace std;
int n;
const int N = 1e5+10;
int q[N];
void quck_sort(int q[], int l, int r)
{
if(l>=r) return;
int i = l-1, j = r+1, x = q[l+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]);
}
quck_sort(q, l, j);
quck_sort(q, j+1, r);
}
int main()
{
cin>>n;
for(int i = 0;i<n;i++)
cin>>q[i];
quck_sort(q, 0, n-1);
for(int i = 0;i<n;i++)
cout<<q[i]<<" ";
return 0;
}
- 以i为分隔的模板
#include<iostream>
using namespace std;
int n;
const int N = 1e5+10;
int q[N];
void quck_sort(int q[], int l, int r)
{
if(l>=r) return;
int i = l-1, j = r+1, x = q[l+r+1>>1];
while(i<j)
{
do i++;while(q[i]<x);
do j--;while(q[j]>x);
if(i<j) swap(q[i], q[j]);
}
quck_sort(q, l, i-1);
quck_sort(q, i, r);
}
int main()
{
cin>>n;
for(int i = 0;i<n;i++)
cin>>q[i];
quck_sort(q, 0, n-1);
for(int i = 0;i<n;i++)
cout<<q[i]<<" ";
return 0;
}
归并排序模板
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++)
q[i] = tmp[j++];
}
二分模板
int l = 0, r = n-1;
while(l<r)
{
int mid = l+r>>1;
if(check(mid) r = mid;
else l = mid+1;
}
int l = 0, r = n-1;
while(l<r)
{
int mid = l+r+1>>1;
if(check(mid)) l = mid;
else r = mid -1;
}