We can use a lot of algorithmic design techniques. The insertion sort is an incremental method that adds new elements to an array that is already lined up. Consider a design method called "Divide and Conquer".
2.3.1 Division and Treatment method
Divide and conquer the idea of the law: The original problem is divided into several smaller but similar to the original problem of sub-problem, the recursive solution of these sub-problems, and then merge the solution of these sub-problems to establish the solution of the original problem. The divide-and-conquer pattern has three steps at each level of recursion:
decomposition of the original problem is a number of sub-problems;
solve These sub-problems, solve each sub-problem recursively, if the sub-problem size is small enough, then the direct solution;
The solution of the Jia Cheng original problem of merging these sub-problems.
The merge sort algorithm completely follows the divide-and-conquer mode and operates as follows:
decomposition: decompose the sequence of n elements to be sorted into two sub-sequences with N/2 elements;
Workaround: sort two sub-sequences recursively by using merge sort;
Merge: merges sorted sub-sequences to produce sorted answers.
When the ordered sequence length is 1 o'clock, the recursion "starts to pick up".
The following is the pseudo-code for merging this step, with a time complexity of Theta (n).
//MERGE Pseudo-codeN1 = Q-p +1N2= R-Q let l[1.. n1+1] and r[1.. n2+1] BeNewArrays fori =1To N1 L[i]= A[p + I-1] forj =1To N2 R[i]= a[q+J] L[n1+1] =∞r[n2+1] =∞i=1J=1 forK =p to RifL[i] <=R[j] A[k]=L[i] I= i +1 ElseA[K] =R[j] J= j +1
Note the point:
1, from the left and right two sequence to remove the smallest number in order to deposit the original array;
2, the left and right two sub-sequences increment respectively, in which sub-column to select a number, the sequence subscript plus 1;
3, in order not to confirm that the sub-sequence is empty each time, to put a "sentinel" at the end of the subsequence, this card is very large, when it touches this card, it must be the number of the other sequence is selected, when the two sub-sequence reached the "Sentinel card", at this time all the numbers are stored in the original array (by the number of iterations of the Loop Head control) When the length of the left and right sequence is inconsistent, the Sentinel card will play the power, two sub-sequence length same time, at the same time to reach the last card, then the "Sentinel card" will not function;
4, in addition, it is necessary to open up new arrays to store each sub-sequence, pay attention to the confirmation of the subscript, especially when calculating the length of the sub-sequence do not be mistaken.
Introduction to Algorithms reading Notes--chapter 2.3 Design algorithm