本文仅供个人记录、分享
快速排序
快排是经典的排序算法之一,其平均的时间复杂度为O(nlogn)
模板:
785. 快速排序 - AcWing题库
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
int n;
int q[N];
void quick_sort(int q[],int l,int r){
if (l >= r) return;
int x = q[l + r >> 1],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;
}
归并排序
归并排序也用到了分治的思想。其时间复杂度为O(nlogn)。
1.确定分界点 mid=(l+r)/2
2.先递归排序 left和 right
3.归并——合二为一。(核心)
模板:
787. 归并排序 - AcWing题库
#include <iostream>
using namespace std;
const int N = 1e5 +10;
int q[N],tmp[N]; //用来存答案的数组
int n;
void merge_sort(int q[], int l, int r)
{
if(l >= r) return;
int mid = l + r >> 1; //位运算,相当于(l + r) / 2
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(i = l, j = 0; i <= r; i ++, j ++) q[i] = tmp[j]; //将tmp数组中的值复制到q数组中
}
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;
}
标签:sort,int,基础,mid,while,算法,quick,排序
From: https://www.cnblogs.com/SoftYurong/p/17044459.html