voidMerge (ElementType a[],elementtype temp[],intLeft,intRight,intrightend) { intTemp,i, Leftend,count; Leftend=right-1;//Super Error Count=rightend-left+1; Temp=Left ; while(left<=leftend&& right<=rightend)//Super Error {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++]; for(i =0; I < count; i++,rightend--) A[rightend]=temp[rightend];//Super Error}void(ElementType A[],elementtype temp[],intLeft,intrightend) { intCenter; if(left<rightend) {Center= (left+rightend)/2; Msort (A,temp,left,center); Msort (A,temp,center+1, Rightend); Merge (A,temp,left,center+1, Rightend); }} voidM_sort (ElementType a[],intN) { /*Merge Sort*/ElementType*Tmpa; Tmpa= (ElementType *)malloc(nsizeof(ElementType)); if(Tmpa! =NULL) {Msort (A, Tmpa,0, N-1 ); Free(TMPA); } Elseprintf"Lack of space"); }
Error Analysis: 1. Will leftend=rightend-1; It is not clear that Leftend is connected to right.
2.left<=leftend error is written <, limit case, only 2 elements of time, left=0,leftend=0,right=1,right=1;
3.a[rightend]=temp[rightend]; wrongly written. Temp[rightend]=a[rightend];
Algorithm Analysis:
Merge implements the merging of 2 ordered sequences.
Left represents the starting position of the first ordered sequence, Leftend represents the subscript for the last element of the first ordered sequence, and right represents the starting subscript for the second ordered sequence, and the default leftend is adjacent to right.
Rightend represents the subscript for the last element of the second sequence. Temp array temporarily holds the sorted sequence.
When A[left]<=a[right], the first element of the left sequence is smaller than the first element on the right, and the first element of the left sequence is placed in temp. At the same time left++,temp++, continue to compare a[left]<=a[right].
When A[left]>a[right], vice versa.
When one sequence is all placed in temp, the other sequence is copied directly to temp.
Msort recursive implementation of sorting.
Center divides the sequence into 2 groups.
Recursively msort the two groups, calls merge, and implements sorting.
Recursive algorithm for merging sort