Sort the quick sort (bottom)

Source: Internet
Author: User

Quick Sort Optimization

The quick line is can be optimized, then what can be optimized, is it the same as you think? Let's look down.

  1, optimize the selection of the pivot value

If the PivotKey we have selected is in the middle of the entire sequence, then we can divide the whole sequence into fractional and large sets of numbers. But notice, what I just said was, "if ... Is the middle, so what if the pivotkey we choose is not the middle number? For example, we used the array {9,1,5,8,3,7,4,6,2}, by the code "Pivotkey=arr[low"; Know that we should pick 9 as the first pivot PivotKey. At this time, after a round of "pivot=partition (arr,1,9);" After the conversion, it just replaced the position of 9 and 2, and returned 9 to pivot, and the whole series did not change substantially.

That is, the code "Pivotkey=arr[low"; Become a potential performance bottleneck. The speed of the sort depends on the key of the Arr[low] at the position of the entire sequence, Arr[low] is too small or too large to affect performance (for example, 5 in the first example is an intermediate number, whereas the second example is a number that is too large for the entire sequence). Because in reality, the series to be sorted is very likely to be basically ordered, at this point, it is always a fixed choice of the first keyword (in fact, regardless of the location of the fixed selection of keywords) as the first pivot has become extremely unreasonable practice.
The improvement approach, it was suggested, should randomly obtain a low and high number of RND, let its keyword l.r[rnd] and l.r[low] Exchange, at this time it is not easy to appear such a situation. This is called a randomly selected pivot method. It should be said that, to some extent, it solves the performance bottleneck in the fast ordering of the basic ordered sequences. However, random on some luck feeling, in case not hit success, random to still very small or very large keyword how to do?
Further improvement, so there is a three-digit (Median-of-three) method . that is, take three keywords first to sort, the middle number as a pivot, generally take the left, right and middle three numbers , can also be randomly selected. In this way, at least the middle number must not be the smallest or largest number, and the probability of taking three numbers as the minimum or maximum number is negligible, so the likelihood of intermediate digits in the more intermediate values is greatly increased. Because the entire sequence is out of order, randomly picking three numbers and taking three numbers from the left and right ends is one thing, and the random number generator itself also brings time overhead, so random generation is not considered.
Let's take a look at the implementation code for the left, right, and middle three numbers, and we'll look at the new partition method.

    /*** Find the subscript for the pivot value and return the element in the * swap Arr[low...high] To move the pivot value to the correct position *@paramarr *@paramLow *@paramHigh *@return     */    Private Static intPartitionint[] arr,intLowintHigh ) {        //Select the second largest int m = low + (high-low)/2 from the first, middle, and last three elements;        if (Arr[low] > Arr[high]) {swap (Arr,low,high);        /* Swap the left and right data to ensure that the ieft side is small */} if (Arr[m] > Arr[high]) {swap (arr,high,m);        /* Swap intermediate and right data to ensure middle smaller */} if (Arr[m] > Arr[low]) {swap (arr,m,low); /* Swap the middle and left data to ensure that the right side is small */}intPivotvalue = Arr[low];//Select Arr[low] as the pivot value//scan from both ends to the center to move the pivot value to the correct position         while(Low <High ) {             while(Lowpivotvalue) { High--;                         } swap (Arr,low,high); //swap records that are smaller than the pivot value to the low end             while(Lowpivotvalue) { Low++;                            } swap (Arr,low,high); //switching records larger than pivot values to high-end        }        returnLow ; }

In this way, it is reasonable to guarantee the value of the hub, of course, if the series is particularly large, it is possible to carry out nine-digit (median-of-nine), which is divided into three samples from the array, take three numbers at a time, three sample each to remove the median, and then from the three median and then take a medium number as the pivot.

  2, optimize the unnecessary exchange

Directly on the code

    /*** Find the subscript for the pivot value and return the element in the * swap Arr[low...high] To move the pivot value to the correct position *@paramarr *@paramLow *@paramHigh *@return     */    Private Static intPartitionint[] arr,intLowintHigh ) {        //Select the second largest from the first, middle, and last three elements        intm = low + (high-low)/2; if(Arr[low] >Arr[high])        {swap (Arr,low,high); /*swap the left and right data to ensure that the ieft side is small*/        }        if(Arr[m] >Arr[high])        {swap (ARR,HIGH,M); /*Swap intermediate and right data to ensure the middle is small*/        }        if(Arr[m] >Arr[low])        {swap (Arr,m,low); /*swap the middle and left data to ensure that the right side is small*/        }                intPivotvalue = Arr[low];//Select Arr[low] as the pivot value//scan from both ends to the center to move the pivot value to the correct position         while(Low <High ) {             while(Lowpivotvalue) { High--; } Arr[low] = Arr[high];                         //swap records that are smaller than the pivot value to the low end             while(Lowpivotvalue) { Low++; } Arr[high] =arr[low];                            //switching records larger than pivot values to high-end} Arr[low] = Pivotvalue; returnLow ; }

  3. Sorting scheme when optimizing small sequence 

If the array is very small, the quick sort is not as good as the direct insert sort (direct insert is the best performance in a simple sort). The reason for this is that a recursive operation is used for fast sequencing, which can be ignored in the case of large numbers of data, which is negligible relative to its overall algorithm advantage, but if the array has only a few records that need to be sorted, the efficiency of fast sorting is lower and the next Qsort method needs to be improved.

    /*** Sequence arr[low for sequences in arr: High] for quick sorting *@paramarr *@paramLow *@param High*/    Private Static voidQSort (int[] arr,intLowintHigh ) {        intPivotKey; if (High-Low > 7) {//find the location of the pivot value, at which point Arr[low,pivotkey-1] is less than (greater than) Arr[pivotkey],arr[pivotkey+1...high] is greater than (less than) Arr[pivotkey]PivotKey =partition (Arr,low,high); QSort (Arr,low,pivotkey-1);//quick sorting of arr[low...pivotkey-1]QSort (Arr,pivotkey+1,high);//quick sorting of Arr[pivotkey+1...high]}Else {strainghtinsertsort (Arr,low,high); }    }    /*** Direct insert sort for sequence Arr[low...high]a *@paramarr *@paramLow *@param High*/    Private Static voidStrainghtinsertsort (int[] arr,intLowintHigh ) {         for(inti=low+1; i<=high; i++) {//Insert Arr[i] into the ordered list             for(intJ=i-1; j>=0&&arr[j]>arr[j+1]; j--) {//ARR[LOW...J] is an ordered listSwap (arr,j,j+1); }        }    }

And so on, other aspects of optimization can be done, more optimization will be handed to you!

Sort the quick sort (bottom)

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.