There are many algorithms that are recursive in structure: to solve a given problem, the algorithm needs to call itself one or more times to solve the related problem. These algorithms usually adopt a divide-and-conquer strategy: The original problem is divided into N small scale and the structure is similar to the original problem, the recursive solution to these child problems, and then merge the results, you can get the solution of the original problem.
The divide-and-conquer model generally has three steps in recursion
Decomposition: To decompose the original problem into a series of subclass problems
Solving: recursive solutions to the problem of each child. If the child problem is small enough, it is solved directly.
Merging: Merging the results of a child problem into the solution of the original problem.
The merging sort is completely in accordance with the above mode in the algorithm, the operation is as follows.
Decomposition: The N/2 of n elements into a sequence of elements
Solve: Recursively sort two subsequence with merge sort method
Merging: Merging the results of a child problem with the solution of the original problem.
The following is the source code implementation
void mergesort (int a[],int left,int right) {int i;//guaranteed to have at least two elements if (left < right) {i = (left+right)/2; MergeSort (A,lef T,i); MergeSort (A,i+1,right); Merge (A,left,right); } void Merge (int a[],int left,int right) {int begin1 = left; int mid = (left+right)/2; int begin2 = mid+1; int k=0; T newarraylen = right-left+1; int *b = (int*) malloc (newarraylen*sizeof (int)); while (Begin1<=mid && begin2<=right) {if (a[begin1]<=a[begin2]) b[k++] = a[begin1++]; else b[k++] = A[beg In2++]; while (begin1<=mid) b[k++] = a[begin1++]; while (begin2<=right) b[k++] = a[begin2++]; Copyarray (B,a,newarraylen,left); Free (b); /** * Copy array * Source: Source Array * dest: Destination array * len: source Array length * First: Destination array start position */void Copyarray (int source[], int dest[],int len,in t (int i; int j=first; for (i=0;i<len;i++) {dest[j] = Source[i]; j + +}} void Mergesorttest () {int a[] = {5, 18, 151, 138, 160, 63, 174, 169, 79, 200}; int len = sizeof (a)/sizeof (int); Showarray (A,len); MergeSort (a,0,len-1); ShowArray (A,len); }