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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| #include <bits/stdc++.h> #define fast \ std::ios::sync_with_stdio(false); \ std::cin.tie(nullptr); using namespace std; typedef long long ll; const int N = 1e6 + 10; int a[N], tmp[N];
//归并排序 //合并两个有序表 void Merge(int *a, int *tmp, int l, int mid, int r) { int i = l, j = mid + 1, k = l; while (i != mid + 1 && j != r + 1) { if (a[i] > a[j]) { tmp[k++] = a[j++]; } else { tmp[k++] = a[i++]; } } while (i != mid + 1) { tmp[k++] = a[i++]; } while (j != r + 1) { tmp[k++] = a[j++]; } for (i = l; i <= r; i++) { a[i] = tmp[i]; } }
//归并排序 void MergeSort(int *a, int *tmp, int l, int r) { if (l < r) { int mid = l + (r - l) / 2; MergeSort(a, tmp, l, mid); MergeSort(a, tmp, mid + 1, r); Merge(a, tmp, l, mid, r); } }
int main() { fast; int n; cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; }
MergeSort(a,tmp,1,n);
for (int i = 1; i <= n; i++) { cout << a[i] << ' '; } return 0; }
|