算法思想:
先假设length=1; 表示先将相邻的2个元素进行排序。A[0]与A[1],A[2]与A[3].............A[N-2]与A[N-1](N为偶数 假设)
然后length=2;A[0]A[1]是有序序列,与A[2]A[3] 进行2个有序序列的归并。
依次类推。
void Merge_Pass(ElementType A[],ElementType Temp[],int N,int length) { int i,j; for(i=0;i<N-2*length;i+=2*length) Merge1(A,Temp,i,i+length,i+length*2-1); if (i+length<N) Merge1(A,Temp,i,i+length,N-1);//超级错误 else { for(j=i;j<N;j++) Temp[j]=A[j]; } } void Merge_Sort(ElementType A[],int N) { int length; ElementType *Temp; Temp = (ElementType *)malloc( N * sizeof( ElementType ) ); length=1; if (Temp!=NULL) { while(length<N) { Merge_Pass(A,Temp,N,length); length=length*2; Merge_Pass(Temp,A,N,length); length=length*2; } } else printf("error\n"); } void Merge1(ElementType A[],ElementType Temp[],int Left,int Right,int RightEnd) { int temp,i, LeftEnd,count; LeftEnd=Right-1; count=RightEnd-Left+1; temp=Left; while(Left<=LeftEnd&& Right<=RightEnd) { if(A[Left]<=A[Right]) Temp[temp++]=A[Left++]; else Temp[temp++]=A[Right++]; } while(Left<=LeftEnd) Temp[temp++]=A[Left++]; while(Right<=RightEnd) Temp[temp++]=A[Right++]; }
错误分析:
Merge1(A,Temp,i,i+length,N);应该有N个元素,最后一个元素的下标是N-1!!!!!!!!!!!!!
时间: 2024-10-19 15:59:29