1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| #include <bits/stdc++.h> using namespace std; void merge(int a[],int n,int left ,int mid,int right); void merge_sort(int a[],int n,int left,int right); const int Maxn=5e5; const int Sentinel=0x3f3f3f3f; int L[Maxn/2],R[Maxn/2]; int cnt; int main() { int n; int a[1000]; cin>>n; for(int i=0;i<n;i++) cin>>a[i]; merge_sort(a,n,0,n); for(int i=0;i<n;i++) cout<<a[i]<<' '; } void merge(int a[],int n,int left ,int mid,int right) { int n1=mid-left; int n2=right-mid; for(int i=0;i<n1;i++) L[i]=a[left+i]; for(int i=0;i<n2;i++) R[i]=a[mid+i]; L[n1]=R[n2]=Sentinel; int i=0,j=0; for(int k=left;k<right;k++) { cnt++; if(L[i]<R[j]){ a[k]=L[i++]; } else{ a[k]=R[j++]; } } } void merge_sort(int a[],int n,int left,int right) { if(left<right) { int mid=(left+right)>>1; merge_sort(a,n,left,mid); merge_sort(a,n,mid+1,right); merge(a,n,left,mid,right); } }
|