归并排序算法实现:
#include<stdio.h> #include<stdlib.h> #define FatalError( Str ) fprintf( stderr, "%s ", Str ), exit( 1 ) typedef int ElementType; void Merge(ElementType A[],ElementType TmpArray[],int lpos,int rpos,int rightend) { int i,leftend,NumElements,TmpPos; leftend=rpos-1; TmpPos=lpos; NumElements=rightend-lpos+1; while(lpos<=leftend&&rpos<=rightend) { if(A[lpos]<=A[rpos]) TmpArray[TmpPos++]=A[lpos++]; else TmpArray[TmpPos++]=A[rpos++]; } while(lpos<=leftend) TmpArray[TmpPos++]=A[lpos++]; while(rpos<=rightend) TmpArray[TmpPos++]=A[rpos++]; //由于每次将临时数组中的元素复制回原来数组时,不能从第一个开始复制,只是从刚刚合并的那一部分复制,所以记录要合并的长度 for(i=0;i<NumElements;i++,rightend--) A[rightend]=TmpArray[rightend]; } void Msort(ElementType A[],ElementType TmpArray[],int left,int right) { int Center; if(left<right) { Center=(left+right)/2; Msort(A,TmpArray,left,Center); Msort(A,TmpArray,Center+1,right); Merge(A,TmpArray,left,Center+1,right); } } void MergeSort(ElementType A[],int N) { ElementType *TmpArray; TmpArray=malloc(sizeof(ElementType)*N); if(TmpArray!=NULL) { Msort(A,TmpArray,0,N-1); free(TmpArray); } else FatalError("No space for tmp array[]"); } void Print(int A[],int N) { int i; for(i=0;i<N;i++) printf(" %d ",A[i]); } int main() { int arr[10]={2,87,39,49,34,62,53,6,44,98}; Print(arr,10); printf(" "); MergeSort(arr,10); Print(arr,10); printf(" "); return 0; }
运行结果如下: