#include <iostream>using namespace std;void merge(int a[], int first, int mid, int last, int c[]){ int i = first,j = mid + 1; int m = mid, n = last; // k 的值與 i的值必須相等,要不無法把c的值回寫給a int k = first; //都還沒有到數組的頭 while (i<=m && j<=n) { if (a[i] <= a[j]) { //新數組加插入較小的元素 c[k++] = a[i++]; } else { c[k++] = a[j++]; } } //如果i的部分還沒有完全插入到數組就將剩餘部分加入 if (i <= m) { while (i<=m) c[k++] = a[i++]; } if (j <= n) { while (j<=n) c[k++] = a[j++]; } //回寫資料給a,如果不回寫,a就永遠不會被排序 for(int i=first;i<=last;i++) a[i] = c[i];}void mergeSort(int a[], int first, int last, int temp[]){ if (first < last) { int mid = (last + first) / 2; mergeSort(a, first, mid, temp); mergeSort(a, mid+1, last, temp); merge(a, first, mid, last, temp); }}int main(){ int a[] = {3, 20, 32, 90, 23, 41, 5, 3, 6, 4, 7, 5, 7, 4}; int b[sizeof(a) / sizeof(*a)]; mergeSort(a, 0, sizeof(a) / sizeof(*a), b); //output for(int i=0; i<sizeof(a) / sizeof(*a); i++) cout << b[i] << ' '; cout << endl; return 0;}
參考:
http://baike.baidu.com/view/90797.htm
http://zh.wikipedia.org/wiki/%E5%BD%92%E5%B9%B6%E6%8E%92%E5%BA%8F
http://blog.csdn.net/morewindows/article/details/6678165