参考网址:http://blog.csdn.net/morewindows/article/details/6678165
// MergeSort.cpp : 定义控制台应用程序的入口点。 //归并排序 #include "stdafx.h" #include <cstdlib> //合并两个有序数组 void mergeArray(int * array,int first,int mid,int last,int * temp){ int i = first; int j = mid + 1; int k = first; while (i <= mid && j <= last){ if (array[i] < array[j]){ temp[k++] = array[i++]; } else{ temp[k++] = array[j++]; } } //将剩余部分插入 while (i <= mid){ temp[k++] = array[i++]; } while (j <= last){ temp[k++] = array[j++]; } //让array 数组 部分有序 for (int i = first; i <= last; i++){ array[i] = temp[i]; } } void merge(int * array,int first,int last,int * temp){ if (last > first){ int mid = (first + last) / 2; merge(array,first,mid,temp);//前半部分有序 merge(array,mid+1,last,temp);//右半部分有序.. mergeArray(array,first,mid,last,temp); } } void mergeSort(int * array,int num){ int * tempArray = (int *) malloc(sizeof(int) * num); merge(array,0,num-1,tempArray); free(tempArray); } static int testArray[] = {33,22,99,77,66,44,55,88,11,100}; int _tmain(int argc, _TCHAR* argv[]) { mergeSort(testArray,10); for (int i = 0; i < 10; i++){ printf("%d\t",testArray[i]); } return 0; }
原文地址:http://blog.csdn.net/fuming0210sc/article/details/45457977