归并排序(c++) #include<iostream> #include<cstdio> #include<algorithm> using namespace std; int n; int x[10]; void Merge(int lo, int mi, int hi) { int len1 = mi - lo; int len2 = hi - mi; int* a = new int[len1]; int* b = new int[len2]; for(int i = 0; i < len1; i++){ a[i] = x[lo + i]; } for(int i = 0; i < len2; i++){ b[i] = x[mi + i]; } for(int i = 0, j = 0, k = lo;i < len1 || j < len2;){ if((i < len1) && (!(j < len2) || (a[i] >= b[j]))){ x[k++] = a[i++]; } if((j < len2) && (!(i < len1) || (b[j] > a[i]))){ x[k++] = b[j++]; } } } void mergesort(int lo, int hi){ if(hi - lo < 2){ return; } else{ int mi = (lo + hi) / 2; mergesort(lo, mi); mergesort(mi, hi); Merge(lo, mi, hi); } } int main() { freopen("in.txt","r",stdin); cin >> n; for(int i = 0; i < n; i++){ cin >> x[i]; } mergesort(0,n); for(int i = 0; i < n;i++){ cout << x[i] << " "; } return 0; }