标签:
#include <iostream> #include <cstdio> const int MAXN = 100002; using namespace std; int array[MAXN], array2[MAXN]; void Merge(int low, int high){ int i = low; int mid = (low + high)/2; int j = mid+1; int k = low; while(i <= mid && j <= high){//比较两个数组,把其中最小的加进去 if(array[i] <= array[j]){ array2[k++] = array[i++]; }else { array2[k++] = array[j++]; } } while(i <= mid){//如果前者没有加完, 则把前面的数组里的数加进去 array2[k++] = array[i++]; } while(j <= high){//意义同上, 两者只会有一个数组有空余 array2[k++] = array[j++]; } for(int s = low; s <= high; s++){ array[s] = array2[s]; } } void MSort(int low, int high){//分治 if(low == high){ array2[low] = array[low]; }else { int mid = (low + high) /2; MSort(low, mid); MSort(mid+1, high); Merge(low, high);//合并 } } int main() { for(int i = 0; i < 10; i++){ array[i] = 10 - i; printf("%d ", array[i]); } printf("\n"); MSort(0, 9); for(int i = 0; i < 10; i++){ printf("%d ", array[i]); } return 0; }
标签:
原文地址:http://www.cnblogs.com/cshg/p/5723251.html