Merge sort toO(NlognThe worst time to run, while the number of comparisons used is almost optimal, it is a good implementation of recursive algorithms. The basic operation of this algorithm is to combine two sorted tables because the two tables are sorted, saying that if the output is placed in a third table, the algorithm can be completed by sequencing the input data. The basic merging algorithm is to take two input arraysAand theB, an output arrayC, and three countersaptr,bptr,Cptr, they are positioned at the beginning of the corresponding array. A[aptr]and theB[bptr]the smaller ones are copied toC, the relevant counter advances one step forward, and when one of the input tables is exhausted, copies the remainder of the other table toCthe.
void Msort (int a[],int temp[],int begin,int end) {int center;if (begin<end) {center= (begin+end)/2; Msort (A,temp,begin,center); Msort (a,temp,center+1,end); merge (a,temp,begin,center+1,end);}} void mergesort (int a[],int length) {int *temparray; temparray= (int *) malloc (length*sizeof (int)); Temparray) {printf ("Out of space\n"); exit (-1);} Msort (a,temparray,0,length-1); free (temparray);} void merge (int a[],int temp[],int left,int right,int rightend) {int Leftend,i;int apos,bpos,temppos=left;leftend= right-1; apos=left;//the starting position of both counters bpos=right; while (apos<=leftend&&bpos<=rightend)//When the input array is not complete {if (A[apos]<=a[bpos]) {Temp[temppos]=a[apos]; apos++;temppos++;} else if (A[apos]>a[bpos]) {Temp[temppos]=a[bpos]; bpos++;temppos++;} else//is equal to copy the past {temp[temppos]=a[apos];temp[temppos+1]=a[bpos];temppos+=2; apos++; bpos++;}} Copy all the rest to C while (Apos<=leftend) temp[temppos++]=a[apos++];while (bpos<=rightend) temp[temppos++]=a[bpos++ ];//copy the final array into the original array for (i=0;i<temppos;i++) a[i]=temp[i];}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C-language implementation of sorting algorithm-merge sort