#include <iostream> #include <stdio.h> using namespace std; const int N = 10e6 + 10; int n; int q[N],tmp[N]; void merge_sort(int q[], int l, int r) { if (l >= r) return; int mid = (l + r)/ 2;//找到分界点 merge_sort(q, l, mid); merge_sort(q, mid + 1, r);//对左右两段进行递归 int k = 0; int i = l; int j = mid + 1; while (i <= mid && j <= r) { if (q[i] <= q[j]) tmp[k++] = q[i++]; if (q[i] > q[j]) tmp[k++] = q[j++]; }//将较小的数赋给tmp while(i<=mid) tmp[k++] = q[i++]; while(j<=r) tmp[k++] = q[j++];//若有一段用完,将另一段的剩余部分赋给tmp for (i = l,j = 0; i <= r; i++, j++) { q[i] = tmp[j]; }//将tmp重新赋给原数组 } int main() { cin >> n; for (int i = 0; i < n; i++) cin >> q[i]; merge_sort(q, 0, n-1); for (int i = 0; i < n; i++) printf("%d ", q[i]); return 0; }
标签:sort,tmp,归并,merge,int,mid,++,排序 From: https://www.cnblogs.com/muzhaodi/p/18002294