/* * description: 归并排序示例 * writeby: nick * date: 2012-10-23 16:35 * */ #include <iostream> #define maxN 10 using namespace std; template <class Item> void merge(Item a[], int l, int m, int r) { int i,j; Item tmp[maxN]; for(i=l; i<=m; i++) tmp[i] = a[i]; // / for(j=m+1; j<=r; j++) tmp[m+1+r-j] = a[j]; i=l; j=r; for(int k=l; k<=r; k++) a[k] = (tmp[i]<tmp[j])? tmp[i++] : tmp[j--]; } template <class Item> void mergesort(Item a[], int l, int r) { if(r <= l) return; int m = (r+l) / 2; mergesort(a, l, m); mergesort(a, m+1, r); merge(a, l, m, r); } int main() { int a[10] = {0,2,8,1,3,6,4,5,7,9}; mergesort(a, 0, 9); for(int i=0; i<10; i++) cout << a[i] << " "; return 0; }