概述:额,还是举个栗子吧:
初始序列[ 98 , 1 , 23 , 4 , 2 , 9 , 8 , 18]
//第一步[ 98 | 1 | 23 | 4 | 2 | 9 | 8 | 18]
//第二步[ 1 98 | 4 23 | 2 9 | 8 18]
//第三步[ 1 4 23 98 | 2 8 9 18]
//第三步[ 1 2 4 9 18 23 98]
排序完成:
时间复杂度:o(nlog(2)n)
核心代码:
void Merge(int A[],int Temp[],int L,int R,int RightEnd)//合并两个有序序列
{
int LeftEnd=R-1;
int p=L,i;
int num=RightEnd-L+1;
while(L<=LeftEnd&&R<=RightEnd)
if(A[L]<=A[R])
Temp[p++]=A[L++];
else
Temp[p++]=A[R++];
while(L<=LeftEnd)
Temp[p++]=A[L++];
while(R<=RightEnd)
Temp[p++]=A[R++];
for(i=0;i<num;i++,RightEnd--)
A[RightEnd]=Temp[RightEnd];
}
void MSort(int A[],int Temp[],int L,int RightEnd)
{
int center;
if(L<RightEnd)
{
center=(L+RightEnd)/2;
MSort(A,Temp,L,center);
MSort(A,Temp,center+1,RightEnd);
Merge(A,Temp,L,center+1,RightEnd);
}
}
void Merge_sort(int A[],int N)
{
int *Temp=(int *)malloc(N*sizeof(int));
if(Temp)
{
MSort(A,Temp,0,N-1);
free(Temp);
}
else
printf("no space!\n");
}
测试样例
int main(){
int A[]={1,3,63,5,78,9,12,52,8};
printf("Previous Arrary:");
for(int i=0;i<9;++i)
printf(" %d",A[i]);
Merge_sort(A,9);
printf("\nSorted Arrary:");
for(int i=0;i<9;++i)
printf(" %d",A[i]);
printf("\n");
return 0;
}
运行结果:
Previous Arrary: 1 3 63 5 78 9 12 52 8
Sorted Arrary: 1 3 5 8 9 12 52 63 78
请按任意键继续. . .