思路:
两个有序的区间,合并成一个有序的区间
模拟:
c++代码
usingnamespacestd; constintN=100010; intq[N]; intn; voidmerge_sort(intl,intr) { if (l>=r) return; intmid=l+r>>1; inti=l;intj=mid+1; //整里子区间merge_sort(l,mid);merge_sort(mid+1,r); inttemp[N]; intt=0; //合并子区间while (i<=mid&&j<=r) { if (q[i] <q[j]) temp[t++] =q[i++]; elsetemp[t++] =q[j++]; } for (i;i<=mid;i++) temp[t++] =q[i]; for (j;j<=r;j++) temp[t++] =q[j]; for (inti=l,j=0;l<=r&&j<=t;j++,i++) q[i] =temp[j]; } intmain() { scanf("%d",&n); for (inti=0; i<n; i++) scanf("%d",&q[i]); merge_sort(0,n-1); for (inti=0;i<n;i++) printf("%d ",q[i]); }