1 voidSolution::d Evideconquersort (vector<int>&VEC)2 {3 intleft =0;4 intright = Vec.size ()-1;5 mergesort (VEC, left, right);6 }7 8 voidSolution::mergesort (vector<int>& VEC,intLeftintRight )9 {Ten if(Left <Right ) One { A intMid = (left+right)/2; - mergesort (VEC, left, mid); -MergeSort (VEC, mid+1, right); the merge (Vec, left, Mid, right); - } - } - + voidSolution::merge (vector<int>& VEC,intLeftintMidintRight ) - { + intLeftnums = Mid-left +1; A intRightnums = right-mid; at - intleftarr[leftnums+1], rightarr[rightnums+1]; - intj =Left ; - inti =0; - for(i =0; i < leftnums; i++) - { inLeftarr[i] =Vec[j]; -J + +; to } +Leftarr[i] = Int_max;//large enough to count as Sentinels - thej = Mid +1; * for(i =0; i < rightnums; i++) $ {Panax NotoginsengRightarr[i] =Vec[j]; -J + +; the } +Rightarr[i] =Int_max; A thei =0; +j =0; - for(intK = left; K < Right +1; k++) $ { $ if(Leftarr[i] <=Rightarr[j]) - { - if(Leftarr[i] = =Int_max) the { - //if this time leftarr[i] is Int_maxWuyi //This means that the elements of Rightarr are also all Int_max. the //to prevent the subscript i overflow - for(k; k < right +1; k++) Wu { -VEC[K] =Int_max; About } $ Break; - } -VEC[K] =Leftarr[i]; -i++; A}Else + { theVEC[K] =Rightarr[j]; -J + +; $ } the } the}
The divide-and-conquer pattern has three steps at each level of recursion:
One: The decomposition of the original problem is a number of sub-problems, these sub-problems are the original problem of small-scale instances
Second: Solve these sub-problems, recursively solve each sub-problem.
Three: The solution of merging these sub-problems, so as to become the solution of the original problem
For example, the above algorithm, the problem of sorting an array into a smaller sorting problem, until the end (Left<right), when all the instances are orderly, because there is only one element, if there is no understanding of the place to draw a picture is very clear
Merge sort:
One: decomposition-sequence of n elements to be sorted each with two sub-sequences of N/2 elements
Two: Solve-sort two sub-sequences recursively by using merge sort
Three: Merge-merges two sorted sub-sequences to produce sorted answers
As far as I am concerned, I have generally understood, so there is not too much explanation notes, if necessary, please leave a message.
Divide and Conquer merge sort