归并排序
归并排序
算法分析
空间效率:\(O(n)\)
时间效率:$每趟归并时间复杂度为O(n),共需 log_{2}n 趟,时间复杂度为n*log_{2}n $
稳定性:稳定
模板
#include<bits/stdc++.h>
using namespace std;
int n;
const int N = 1e5 + 10;
int a[N], t[N];
void mergeSort(int a[], int l, int r) {
if (l >= r) return;
int mid = l + r >> 1;
mergeSort(a,l,mid);
mergeSort(a,mid+1,r);
int i = l, j = mid + 1, k = 0;
while (i<=mid&&j<=r){
if(a[i]<=a[j]) t[k++]=a[i++];
else t[k++]=a[j++];
}
while (i<=mid) t[k++]=a[i++];
while (j<=r) t[k++]=a[j++];
for (int m = l, n = 0; m <=r ; ++m, ++n) {
a[m]=t[n];
}
}
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
mergeSort(a,0,n-1);
for (int i = 0; i < n; i++) printf("%d ", a[i]);
return 0;
}