There are a few things about the optimization of a quick row:
1, reduce the number of swap or directly without swap operations, consider each time (I, J) The exchange of elements, so that the exchange of each element pair into a whole move:
1 //Quick row: Selected pivot point2 intParti (intLointhi)3 {4Swap (Num[lo], Num[lo + rand ()% (Hi-lo +1)]);5 int pivot = Num[lo]; 6 while(Lo <hi)7 {8 while(Lo < hi) && (pivot <= Num[hi]) hi--;9 Num[lo] = Num[hi]; Ten while(Lo < hi) && (Num[lo] <= pivot)) lo++; One Num[hi] = Num[lo]; A } - Num[lo] = pivot; - returnLo; the}
The table now has an underlined code.
2, for the selection of the pivot point, to make the size of the set of left and right as much as possible.
The methods that can be taken are: Random selection method and three-way method.
Compared with the probability of the worst-case scenario, the three methods are more effective than the random selection method to avoid them.
3, for the degradation of the consideration, that is, repeating elements.
You can refine the selected pivot point code above to:
1 //Quick row: Selected pivot point2 intParti (intLointhi)3 {4Swap (Num[lo], Num[lo + rand ()% (Hi-lo +1)]);5 intPivot =Num[lo];6 while(Lo <hi)7 {8 while(Lo <hi)9 {Ten if(Pivot < Num[hi]) hi--; One Else A { -num[lo++] =Num[hi]; - Break; the } - } - while(Lo <hi) - { + if(Num[lo] < pivot)) lo++; - Else + { Anum[hi--] =Num[lo]; at Break; - } - } - } -Num[lo] =pivot; - returnLo; in}
This is true for all the same elements, and the pivot points can be selected at the midpoint without degrading to the worst case. The price is that the actual exchange has changed a lot.
From: I know the answer: http://www.zhihu.com/question/19841543/answer/46760856
Key optimizations for fast sequencing