#include<bits/stdc++.h> #define N 1000 using namespace std; int a[N]; int tmp[N]; void mergesort(int l,int r) { if(l==r) return; int mid=l+r>>1; mergesort(l,mid); mergesort(mid+1,r); int i=l,j=mid+1,tot=l-1; while(i<=mid&&j<=r) { if(a[i]<=a[j]) tmp[++tot]=a[i++]; else tmp[++tot]=a[j++]; } while(i<=mid) tmp[++tot]=a[i++]; while(j<=r) tmp[++tot]=a[j++]; for(int i=l;i<=r;i++) a[i]=tmp[i]; } int main() { int n;cin>>n; for(int i=1;i<=n;i++)cin>>a[i]; mergesort(1,n); for(int i=1;i<=n;i++)cout<<a[i]<<" "; return 0; }
或者:
int a[N]; int tmp[N]; void margesort(int ;l,int r){ if(l==r)return; int mid=l+r>>1; mergesort(l,mid); mergrsort(mid,r); int i=1,j=mid+1; while(i<=mid||j<=r){ if(j==r+1||a[i]<=a[j]) tmp[++tot]=a[i++]; else tmp[++tot]=a[j++]; } for(int i=1;i<=r;i++) a[i]=tmp[i]; } int main(){ mergesort(1,n); }