Algorithm idea:
First assume length=1; Indicates that the adjacent 2 elements are sorted first. A[0] and a[1],a[2] and a[3] ...... A[n-2] and A[n-1] (N is even hypothesis)
Then Length=2;a[0]a[1] is an ordered sequence, with a[2]a[3] to merge 2 ordered sequences.
In turn.
voidMerge_pass (ElementType a[],elementtype temp[],intNintlength) { inti,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);//Super ErrorElse { for(j=i;j<n;j++) Temp[j]=A[j]; }} voidMerge_sort (ElementType a[],intN) {intlength; ElementType*Temp; Temp= (ElementType *)mallocNsizeof(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; } } Elseprintf ("error\n"); } voidMerge1 (ElementType a[],elementtype temp[],intLeft,intRight,intrightend) { intTemp,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++]; Elsetemp[temp++]=a[right++]; } while(left<=leftend) Temp[temp++]=a[left++]; while(right<=rightend) Temp[temp++]=a[right++]; }
Error Analysis:
Merge1 (a,temp,i,i+length,n);
There should be n elements, and the subscript for the last element is n-1!!!!!!!!!!!!!
Non-recursive algorithm for merge sort