1、merge_sort.cpp: 自顶向下,使用递归 #include <stdio.h> //#include <stdlib.h> using namespace std; void merge(int *a,int *temp,int lPos,int rPos,int rEnd) { int i,lEnd,tempPos,cout; lEnd = rPos - 1; tempPos = lPos; cout = rEnd - lPos + 1; while(lPos <= lEnd && rPos <= rEnd) { if(a[lPos] <= a[rPos]) temp[tempPos++] = a[lPos++]; else temp[tempPos++] = a[rPos++]; } if(lPos <= lEnd) temp[tempPos++] = a[lPos++]; if(rPos <= rEnd) temp[tempPos++] = a[rPos++]; for(i = 0;i < cout;i++,rEnd--) { a[rEnd] = temp[rEnd]; } } void msort(int *a, int *temp, int low, int high) { if(low >= high) return; int mid = (low + high) / 2; msort(a, temp, low, mid); msort(a, temp, mid + 1, high); merge(a, temp, low, mid + 1, high); } void merge_sort(int *a, int len) { int *temp = NULL; temp = new int[len]; //temp = (int *)malloc(sizeof(int) * len); if(temp != NULL) { msort(a, temp, 0, len - 1); //free(temp); delete [] temp; } } void print_array(int *a, int len) { int i; for(i = 0; i < len;i++) { printf("%d ", a[i]); } printf("/n"); } int main() { int a[] = {8,0,3,4,2,1,5,6,9,7}; print_array(a, 10); merge_sort(a, 10); print_array(a, 10); return 0; } 2、merge_sort.c:自底向上,使用迭代 #include <stdio.h> #include <stdlib.h> #include <string.h> void print_array(int *a, int len) { int i; for(i = 0;i < len;i++) { printf("%d ", a[i]); } printf("/n"); } //this is down to up merge method. //arg lPos and rPos are the begin of the two part, //and arg step stand by the cout of each part, //and arg len is the length of the a[]. void merge(int *a, int lPos, int rPos, int step, int len) { int len_right, index, lEnd, rEnd; //the length of right part should be compute. if(rPos + step - 1 >= len - 1) len_right = len - rPos; else len_right = step; //index is used to remember the lPos to copy from temp[]. index = lPos; lEnd = rPos - 1; rEnd = rPos + len_right - 1; int *temp = (int *)malloc(sizeof(int) * (step + len_right)); int i = 0; while(lPos <= lEnd && rPos <= rEnd) { if(a[lPos] <= a[rPos]) temp[i++] = a[lPos++]; else temp[i++] = a[rPos++]; } while(lPos <= lEnd) temp[i++] = a[lPos++]; while(rPos <= rEnd) temp[i++] = a[rPos++]; int j; for(j = 0;j < i;j++) { a[index + j] = temp[j]; } free(temp); } //the step is from 1 to until len. void merge_sort(int *a, int len) { int step = 1; while(step < len) { int i; for(i = 0;i <= (len - step - 1);i += (2 * step)) { merge(a, i, i + step, step, len); } step *= 2; } } int main() { int a[] = {2,4,8,0,1,3,7,5,6,9}; print_array(a, 10); merge_sort(a, 10); print_array(a, 10); return 0; }