归并排序(模板题)
题目链接:
https://www.acwing.com/problem/content/description/789/
题解:
1、找分界点。
2、分别排序
3、归并
递归实现
AC代码:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int N = 1e5+5; int a[N],tmp[N]; void merge_sort(int a[],int l,int r){ if(l >= r) return; int mid = (l+r) / 2; merge_sort(a,l,mid); merge_sort(a,mid+1,r); int s1 = l,s2 = mid+1; int s = 0; while(s1 <= mid && s2 <= r){ if(a[s1] <= a[s2]) tmp[s++] = a[s1++]; else tmp[s++] = a[s2++]; } while(s1 <= mid) tmp[s++] = a[s1++]; while(s2 <= r) tmp[s++] = a[s2++]; for(int i=l,j=0;i<=r;j++,i++) a[i] = tmp[j]; } int main(){ int n; scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&a[i]); merge_sort(a,0,n-1); for(int i=0;i<n;i++) printf("%d ",a[i]); return 0; }