Key optimizations for fast sequencing

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.