This is a creation in Article, where the information may have evolved or changed.
Recent interest in go language, found that go language grammar concise, very suitable for the description and implementation of the algorithm, so the merge sort is implemented.
In the example, the queue that needs to be sorted is a sequence of 100 from 100 to 1, and the sorting algorithm is ordered correctly, and the result should be 1 to 100.
Since the maximum value of the array is set to 100, the "Sentinel" is abbreviated to 1000 because it is not the core part of the algorithm, where the "sentinel" Maximum processing is omitted.
1 /*2 go language implementation of merge sort3 */4 Package Main5 6Import FMT"FMT"7 8 Func Main () {9 /*Ten generate queues that need to be sorted 100~1 One */ Alength:= - -A:=make ([]int, Length) -j:=length the fori:=0; i<length;i++{ -a[i]=J -j-- - } + /* - Sort + */ AMergeSort (A,0, length-1) at /* - output sorted Queue - */ - fori:=0; i<length;i++{ - FMT. Println (A[i]) - } in } - /* to Merge Sort + */ -Func mergesort (Arrary []intPintRint) { the * ifp<R { $q:=0Panax Notoginseng if(r-q+1)%2==0{ -Q= (p+r-1)/2 the}Else{ +q= (P+R)/2 A } the + mergesort (arrary,p,q) -MergeSort (arrary,q+1, R) $ Merge (arrary,p,q,r) $ } - } - /* the two column sorted array merge - */WuyiFunc Merge (Arrary []intPintQintRint) { then1:=q-p+1 -n2:=r-Q Wu -L_arr:=make ([]int, (n1+1)) AboutR_arr:=make ([]int, (n2+1)) $ - fori:=0; i<n1;i++{ -l_arr[i]=arrary[p+i] - } Al_arr[n1]= +; + the fori:=0; i<n2;i++{ -r_arr[i]=arrary[q+1+i] $ } ther_arr[n2]= +; theilnum:=0 theirnum:=0 the fori:=p;i<r+1; i++{ - ifl_arr[ilnum]<R_arr[irnum] { inarrary[i]=L_arr[ilnum] theilnum++ the}Else{ Aboutarrary[i]=R_arr[irnum] theirnum++ the } the } +}
C + + implementation
1#include <iostream>2 using namespacestd;3 voidMergeSort (int*,int,int);4 voidMerge (int*,int,int,int);5 intMainvoid)6 {7 //generating arrays to be arranged8 intLength= -;9 int*a=New int[length];Ten for(intI=0, j=length;i<length;i++,j--) One { Aa[i]=J; - } -MergeSort (A,0, length-1); the for(intI=0; i<length;i++) - { -cout<<a[i]<<" "; - } + return 0; - } + /* A A[P...R] at */ - voidMergeSort (int*a,intPintR) - { - if(p<R) - { - intq=0; in //Q to take the floor, or it will overflow when q+1 - if((r-q+1)%2==0) to { +Q= (p+r-1)/2; - } the Else * { $q= (P+R)/2;Panax Notoginseng } - mergesort (a,p,q); theMergeSort (a,q+1, R); + Merge (a,p,q,r); A } the } + /* - A[P...Q],A[Q+1...R] $ */ $ voidMerge (int*a,intPintQintR) - { - intn1=q-p+1; the intn2=r-Q; - Wuyi int*l_arr=New int[n1+1]; the int*r_arr=New int[n2+1]; - for(intI=0; i<n1;i++) Wu { -l_arr[i]=a[p+i]; About } $l_arr[n1]= +; - for(intI=0; i<n2;i++) - { -r_arr[i]=a[q+1+i]; A } +r_arr[n2]= +; the intilnum=0; - intirnum=0; $ for(inti=p;i<r+1; i++) the { the if(l_arr[ilnum]<R_arr[irnum]) the { thea[i]=L_arr[ilnum]; -ilnum++; in } the Else the { Abouta[i]=R_arr[irnum]; theirnum++; the } the } +}