递归版的合并排序,时间复杂度为O(nlogn),空间复杂度为O(n+logn);
算法思想:
利用分而自治的思想,把排序分成两块,每块内部排序,再进行一次遍历排序即可,递归调用此过程即可。
主要代码:
void MergeSort(int *arr,int length){ Msort(arr,arr,0,length-1); } void Msort(int *arr1,int *arr2,int begin,int end){ int arr3[10]; int m; if(begin == end) arr2[begin] = arr1[end]; else{ m = (end + begin)/2; Msort(arr1,arr3,begin,m); Msort(arr1,arr3,m+1,end); sort(arr3,arr2,begin,m,end); } } void sort(int *arr3,int *arr1,int begin,int m,int end){ int i=begin,j=m+1,k,h; for(k=i; i<=m && j<=end;k++){ if(arr3[i] < arr3[j]) arr1[k] = arr3[i++]; else arr1[k] = arr3[j++]; } if(i <= m){ for(h=0; h<=m-i;h++) arr1[k+h] = arr3[i+h]; }else{ for(h=0; h<=end-j;h++) arr1[k+h] = arr3[j+h]; } }
全部代码:
#include <stdio.h> #include <stdlib.h> #include <time.h> int arrtest1[10] = {3,4,7,8,0,9,1,2,6,5}; int arrtest2[10] = {0,1,2,3,4,5,6,7,8,9}; int arrtest3[10] = {9,8,7,6,5,4,3,2,1,0}; void copy(int *from,int *arr,int length); void print(int *arr,int length); void MergeSort(int *arr,int length); void Msort(int *arr1,int *arr2,int begin,int end); void sort(int *arr3,int *arr1,int begin,int m,int end); int main(){ clock_t start,end; int Arr[10]; int i; copy(arrtest1,Arr,10); print(Arr,10); MergeSort(Arr,10); print(Arr,10); start = clock(); for(i=0;i<100000;i++){ copy(arrtest1,Arr,10); //print(Arr,10); MergeSort(Arr,10); //print(Arr,10); } end = clock(); printf("first test:%d ",end-start); start = clock(); for(i=0;i<100000;i++){ copy(arrtest2,Arr,10); //print(Arr,10); MergeSort(Arr,10); //print(Arr,10); } end = clock(); printf("first test:%d ",end-start); start = clock(); for(i=0;i<100000;i++){ copy(arrtest3,Arr,10); //print(Arr,10); MergeSort(Arr,10); //print(Arr,10); } end = clock(); printf("first test:%d ",end-start); getchar(); return 0; } void MergeSort(int *arr,int length){ Msort(arr,arr,0,length-1); } void Msort(int *arr1,int *arr2,int begin,int end){ int arr3[10]; int m; if(begin == end) arr2[begin] = arr1[end]; else{ m = (end + begin)/2; Msort(arr1,arr3,begin,m); Msort(arr1,arr3,m+1,end); sort(arr3,arr2,begin,m,end); } } void sort(int *arr3,int *arr1,int begin,int m,int end){ int i=begin,j=m+1,k,h; for(k=i; i<=m && j<=end;k++){ if(arr3[i] < arr3[j]) arr1[k] = arr3[i++]; else arr1[k] = arr3[j++]; } if(i <= m){ for(h=0; h<=m-i;h++) arr1[k+h] = arr3[i+h]; }else{ for(h=0; h<=end-j;h++) arr1[k+h] = arr3[j+h]; } } void copy(int *from,int *arr,int length){ int i; for(i=0;i<length;i++){ arr[i] = from[i]; } } void print(int *arr,int length){ int i; for(i=0;i<length;i++){ printf("%d ",arr[i]); } printf(" "); }