例如:
以下代码参考自:白话经典算法系列之五 归并排序的实现;原文写的很好,但我稍作了改动,便于理解。
不想多说什么,代码有详细注释,我想关键点是:递归二分、合并的“后序遍历”方法的理解。
#include<iostream> using namespace std; #define MAXSIZE 10 void printArray(int array[],int n) { for(int i = 0; i < n; ++i) cout<<array[i]<<" "; cout<<endl; } //将两个有序数列array[first...mid] 和 array[mid+1...last] 合并。 void mergearray(int array[], int first, int mid, int last, int temp[]) { //cout<<"[mid2] = "<<mid<<endl; cout<<"[ first = "<<first<<" , mid = "<<mid<<" ,last = "<<last <<" ] "<<endl; int part1_first = first, part1_last = mid;//第一部分有序数 int part2_first = mid+1, part2_last = last;//第二部分有序数 int t = 0;//用于temp下标计数 //依次比较两部分有序数,依次将两者中的数(合并)按序存入temp[]中 while (part1_first <= part1_last && part2_first <= part2_last) { if (array[part1_first] <= array[part2_first]) temp[t++] = array[part1_first++]; else temp[t++] = array[part2_first++]; } //将剩余的(有序part1)数存入temp[] while (part1_first <= part1_last) { temp[t++] = array[part1_first++]; } //将剩余的(有序part2)数存入temp[] while (part2_first <= part2_last) temp[t++] = array[part2_first++]; cout<<" temp = "; printArray(temp, MAXSIZE); //放回array[] for (int i = 0; i < t; ++i) { array[first + i] = temp[i]; temp[i] = 0; } cout<<"array = "; printArray(array, MAXSIZE); } void mergesort(int array[], int first, int last, int temp[]) { //通过递归,不断的将数组二分为两部分,最小的数据部分为1个 if (first < last) { int mid = (first + last) / 2; //cout<<"********** mid1 = "<<mid<< " *********"<<endl; cout<<"******* first = "<<first<<" , mid = "<<mid<<" ,last = "<<last <<" ******* "<<endl; mergesort(array, first, mid, temp); //前半部分有序 mergesort(array, mid + 1, last, temp); //后半部分有序 mergearray(array, first, mid, last, temp); //再将两个有序数列比较、合并 } } bool MergeSort(int array[], int n) { /* int *p = new int[n]; if (p == NULL) return false; mergesort(array, 0, n - 1, p); delete[] p; return true;*/ int tempArray[MAXSIZE]={0}; mergesort(array, 0, n - 1, tempArray); return true; } int main() { //int array[MAXSIZE] = {23, 34, 45, 78, 90, 12, 49, 92, 32, 19}; int array[MAXSIZE] = {9,8,7,6,5,4,3,2,1,0}; //int array[ ] = {9,8,7,1,2,3,6,5,4,0,19,18,17,11,12,13,16,15,14,10,29,28,27,21,22,23,26,25,24,20}; //int array[MAXSIZE] = {4,3,2,1}; printArray(array, MAXSIZE); bool bValue = MergeSort(array, MAXSIZE); if(!bValue) { cout<<"MergeSort Failed!! "<<endl; } printArray(array, MAXSIZE); }