#include <iostream> using namespace std; void merge(int a[], int s1, int e1, int s2, int e2) { int n1 = e1 - s1 + 1; int n2 = e2 - s2 + 1; int al[n1]; int ar[n2]; for (int i = 0; i < n1; i++) al[i] = a[i + s1]; for (int i = 0; i < n2; i++) ar[i] = a[i + s2]; int l = 0; int r = 0; int p = s1; while (l < n1 && r < n2) { if (al[l] < ar[r]) { a[p] = al[l]; l++; p++; } else { a[p] = ar[r]; r++; p++; } } while (l < n1) { a[p] = al[l]; l++; p++; } while (r < n2) { a[p] = ar[r]; r++; p++; } } void mergesort(int a[], int s, int e) { if (s < e) { int m = (s + e) / 2; mergesort(a, s, m); mergesort(a, m + 1, e); merge(a, s, m, m + 1, e); } } int main() { int n; cin >> n; int a[n]; for (int i = 0; i < n; i++) cin >> a[i]; mergesort(a, 0, n - 1); for (int i = 0; i < n; i++) cout << a[i] << ' '; return 0; }
标签:归并,int,al,++,ar,n1,n2,排序 From: https://www.cnblogs.com/lf-ancer/p/16733679.html