Sorting algorithm--Quick sort

Source: Internet
Author: User

Iv. Fast Sorting (Quick sort)

Fast sorting is a widely used sort algorithm, which belongs to the Exchange sort class.

Ideas:

  Sorting using recursive algorithms for "Divide and conquer"

Steps:

1) Benchmark case: n=0 or 1, no sorting required, return

2) N>1, take an arbitrary element from the array s ν, called the pivot element (pivot)

3) split:

  Put all elements larger than ν to the right of V, S1

Put the element that is smaller than V to the left of V, S2

4) quickly sort the left and right two intervals recursively until there are only 0 or 1 elements in the sequence

Quicksort (S1)

Quicksort (S2)

Note: You should avoid creating new arrays that occupy additional memory space

Segmentation method:

The 3rd Step Segmentation method is not unique, so it becomes a design decision.

(1) Common, the first element as a hub element

If the input is random, it is possible;

If the input is pre-ordered or reversed, a poor segmentation is produced, all elements are in S1 or S2, and the same is true for all recursion cases.

The time spent is two times, and the pivot element is not valid.

Similarly, there are the larger of the first 2 elements that are selected as the pivot element.

(2) Random selection of base number

  Safe, not always inferior segmentation.

The desired time complexity of O (Nlogn) is reached for the vast majority of input data.

(3) Three-digit median segmentation method (Median-of-three)

Best pivot element: The median of an array n, which is the maximum number of N/2. But it's hard to figure out, and it slows down the speed of the platoon.

General Practice: Use the middle value of the three elements on the left, right, and center positions as the base number .

  Eliminates the bad case for pre-sorted input and reduces the number of comparisons by approximately 14%. avoid the deterioration caused by the "element not being random at the time of entry".   

/* * * Quick-Sort Drivers */ void quicksort (vector<int> &a) {    01);} void quicksort (vector<int int int right)
voidQuicksort (vector<int> &a,intLeftintRight ) {     if(left >= right)return; /*Find pivot Element*/     int Base=Division (A, left, right); intPivot = a[Base]; /*Start splitting*/     inti =Left ; intj =Right ;  while(I <j) {/*find the number less than the pivot element first from right to left*/         while(A[j] >= pivot && i < j) j--; /*then find the number greater than the pivot element from left to right*/         while(A[i] <= pivot && i < j) i++; /*if the two do not intersect, the position of the two number in the array is exchanged*/          if(I <j) Std::swap (A[i], a[j]); }     /*return pivot element to position*/Std::swap (a[Base], a[i]); /*quickly sort the left and right halves in a recursive way*/quicksort (A, left, I-1); Quicksort (A, I+1, right);}
View Code
/** * Use the first element or a random number within [left,right] as the pivot element*/intDivision (vector<int> &a,intLeftintRight ) {        /*The following scenario two selected one*/        /*randomly selects the number in the [Left,right] range as the pivot element*/    inti = rand ()% (right-left+1) + left;//random number in [Left,right]Std::swap (A[left], a[i]); returnLeft ; /*use the first number as the pivot element*/     returnLeft ;} 
View Code

    • Using the three-digit median segmentation method (Median-of-three)
voidQuicksort (vector<int> &a,intLeftintRight ) {    if(left >= right)return; intPivot =Division (A, left, right); inti = left;//starting position, warning sign    intj = Right-1;  while(I <j) {/*starting with left+1 and Right-2 .*/         while(A[++i] <pivot) {}         while(Pivot < a[--J]) {}        if(I <j) Std::swap (A[i], a[j]); Else             Break; } std::swap (A[right-1], a[i]); Quicksort (A, left, I-1); Quicksort (A, I+1, right);}
View Code
intDivision (vector<int> &a,intLeftintRight ) {    intCenter = (left + right)/2; if(A[center] <A[left]) Std::swap (A[left], a[center]); if(A[left] >A[right]) Std::swap (A[left], a[right]); if(A[center] >A[right]) Std::swap (A[right], a[center]); Std::swap (A[center], a[right-1]); returnA[right-1];}
View Code

Analysis: Select the median of a[left],a[center],a[right] as the base value.

First, the three are sorted,a[left]< A[center]<a[right],a[center] is the median of the three, as the hub element pivot, and A[left], A[right] are in the segmentation phase should be in the interval.

Pivot can be placed in a[right-1], and I and J are initialized to left and right-1 during the split phase. A[left]<pivot, so A[left] as a warning mark of J, do not have to worry about J run over the end point, because I will stop at the pivot element, so the pivot is stored at a[right-1] for I provides a warning mark, do not worry I run over the end point.

Complexity of Time:

  N=0 or 1, time is constant, recorded as 1.

N>1, spents: T (N) =t (i) +t (n-i-1) +CN (time spent dividing)

1) Worst case scenario:

The pivot element is always the smallest element, at this time i=0, ignoring the insignificant T (0) =1

T (N) =t (N-1) +CN

T (N-1) =t (N-2) +c (N-1)

......

T (2) =t (1) +c (2)

Add to T (N) =t (1) +c (2+3+4+...+n) =θ (N2)

1) Best case:

The pivot element is just in the middle, simplifying, assuming that two sub-arrays are exactly half the size of the original array

T (n) =2t (N/2) +cn--> t (n)/n=t (N/2)/(N/2) +c

T (N/2)/(N/2) =t (N/4)/(N/4) +c

......

T (2)/2=t (1)/1+c

Add to T (N) =cnlogn+n =θ (NLOGN)

3) Average situation:

  T (N) =O (NLOGN)

Where applicable:

For very small arrays (n<=20), quick sorting is better than inserting a sort. The usual workaround is that for small arrays, instead of using quick sorting recursively, use the sort algorithm that is useful for decimal groups, such as insertion sorting. The cutoff range can be between n = 5~20, and can actually save up to 15% of the elapsed time relative to the fast-row approach.

if (left+<= right) {     //  Use quick sort         quicksort (a,left,right);} Else {      //  Use Insert sort for decimal group     Insertionsort (a,left,right);    }
View Code

STL's sort algorithm, when the data volume is large, uses the fast row, the piecewise recursive sorting, once the segmented data volume is less than a certain threshold, in order to avoid the fast row recursive call brings the excessive extra load, instead inserts the sort. If the recursive hierarchy is too deep, the heap ordering is also used instead.

Sorting algorithm--Quick sort

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.