Algorithm idea: The basic idea is the divide-and-conquer algorithm, that is, a problem is divided into a number of smaller parts of the recursive solution. The specific to the merge sort is to divide the ordered sequence into small sequences, recursively to sort, and then merge.
Steps:
1. Decomposition: Divide n elements into sub-sequences containing N/2 elements
2. Solve: Recursively sort two sub-sequences with merge sort
3. Merging: Merging two sorted sub-sequences to get sorted results
When a subsequence is sorted, its length is 1 o'clock recursion ends.
Algorithmic complexity: O (NLGN)
Code implementation:
voidDivide_sort (intArr[],intPintR) { if(p<r) {intQ = (r + P)/2; Divide_sort (arr, p, q); Divide_sort (arr, q+1, R); Merge_sort (arr, p, Q, R); }}voidMerge_sort (intArr[],intPintQintR) { intN1 = Q-p +1; intN2 = R-Q; int*l =New int[N1]; int*r =New int[N2]; memcpy (L, arr+p, n1*sizeof(int)); memcpy (R, arr+q +1, n2*sizeof(int)); intI, J; I= j =0; intK =p; while(i!=n1&&j!=n2) { if(l[i]<=R[j]) {Arr[k+ +] = l[i++]; } Else{arr[k+ +] = r[j++]; } } while(i!=N1) {Arr[k+ +] = l[i++]; } while(j!=n2) {Arr[k+ +] = r[j++]; } delete[] L; Delete[] R;}
Algorithm learning Note (iv): merge sort