重温归并排序
分成小块,回溯时合并
#include <bits/stdc++.h> #define dbug(x) cout << #x << "=" << x << endl #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; const int inf = 0x3f3f3f3f; template<class T>inline void read(T &res) { char c;T flag=1; while((c=getchar())<'0'||c>'9')if(c=='-')flag=-1;res=c-'0'; while((c=getchar())>='0'&&c<='9')res=res*10+c-'0';res*=flag; } const int maxn = 2e5 + 7; int a[10]; void Sort(int, int); void merge(int l, int r) { if(l >= r) return; int mid = (l + r) >> 1; merge(l, mid); merge(mid + 1, r); Sort(l, r); } void Sort(int l, int r) { vector<int> temp; int mid = (l + r) >> 1; int i = l, j = mid + 1; while(i <= mid && j <= r) { if(a[i] < a[j]) { temp.push_back(a[i]); ++i; } else { temp.push_back(a[j]); ++j; } } while(i > mid && j <= r) { temp.push_back(a[j++]); } while(i <= mid && j > r) { temp.push_back(a[i++]); } for (int i = 0; i < r - l + 1; ++i) { a[i + l] = temp[i]; } } int main() { for (int i = 0; i < 10; ++i) { a[i] = 9 - i; } cout << "The initial array: "; for ( int i = 0; i <= 9; ++i ) { cout << a[i] << ' '; } cout << endl; merge(0, 9); cout << "The final array: "; for (int i = 0; i <= 9; ++i) { cout << a[i] << ' '; } cout << endl; return 0; }