归并排序

来源:互联网 发布:xshell linux版 编辑:程序博客网 时间:2024/04/30 01:58

归并排序(Merge Sort)

算法思想:采用分治法,首先将整个数组一分为二,然后将两个子数组分别排列为有序数组,再将两个有序子数组合并为一个有序子数组。其中第二步中对子数组的排序过程也采用上述过程进行,所以这是一个递归算法。

归并排序的时间性能上界是O(N*logN)。归并排序是稳定排序算法。

由于在合并两个有序子数组时需要额外的存储空间,并且还有将数据拷贝到临时数组再拷贝回来的时间开销,所以归并排序不适合内部排序,但归并排序中的Merge()操作是外部排序算法的基础。

#include <stdio.h>#include <stdlib.h> /*将数组A中的两个有序子序列A[Lpos]~A[Rpos-1]和A[Rpos]~A[RightEnd]排列为一个有序子序列,并存放在A[Lpos]~A[RightEnd]中*/void Merge( int A[], int 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++ ){                   A[RightEnd] = TmpArray[RightEnd];                   RightEnd--;         }} void MSort( int A[], int 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( int A[], int N ){         int *TmpArray;                 TmpArray= (int *)malloc( N * sizeof(int) );         if(TmpArray != NULL ){                   MSort( A, TmpArray, 0, N - 1 );                   free(TmpArray);         }         else{                   printf("No space for tmp array!!!\n");         }}