Quick Sort (QuickSort)

Source: Internet
Author: User
Tags benchmark

1. Algorithm Idea
Quick Sort is a sort of divided interchange. It adopts a strategy of division, which is usually referred to as the Division method (Divide-and-conquermethod).

(1) The basic idea of division and Administration Law
The basic idea of divide-and-conquer method is: to decompose the original problem into several sub-problems with smaller size but similar structure to the original problem. Solve these sub-problems recursively, then combine the solutions of these sub-problems into the solution of the original problem.

(2) The basic idea of fast sequencing
Set the current unordered area to be sorted as R[low. High], the basic idea of fast sequencing can be described by using the divide-and-conquer method:
① decomposition:
  In R[low. High] To select a record as the Datum (Pivot), which divides the current unordered division into left and right two smaller sub-intervals r[low. PIVOTPOS-1) and R[pivotpos+1..high], and make all recorded keywords in the left sub-range less than or equal to the datum record (may be remembered as pivot) Keyword Pivot.key, all the recorded keywords in the right sub-range are greater than or equal to Pivot.key, and the Datum record pivot is in the correct position (PIVOTPOS), it does not need to participate in subsequent sorting.
  note:
    The key to partitioning is to require the location of the benchmark record Pivotpos. The results of the partitioning can be simply expressed as (note Pivot=r[pivotpos]):
    r[low. Pivotpos-1].keys≤r[pivotpos].key≤r[pivotpos+1..high].keys
                   which Low≤pivotpos≤high.
② solver:  
       Quick Sort by recursive call to left and right sub-range r[low ... PIVOTPOS-1] and R[pivotpos+1..high] quick sort.
③ combination:  
      because when " At the end of the two recursive calls in the solve step, the left and right two sub-bands are ordered. For a quick sort, the combination step does not have to do anything and can be seen as an empty operation.

Algorithm structure:

1 voidQuickSort (Elemtype r[],intLowintHigh )2 {3     if(Low//boundary conditions, conditions for recursive jumps4     {5         intPivotpos = Partition (R,low,high);//Divide6QuickSort (r,low,pivot-1);//recursive ordering of left interval7QuickSort (r,pivot+1, high);//recursive ordering of right intervals8     }9}

The key of the fast sorting algorithm is to divide the operation, and the performance of the fast sorting algorithm depends mainly on the division operation.

Here is a way to divide the algorithm:

1 intPartition (Elemtype r[],intLowintHigh )2 {3Elemtype pivot = R[low];//Save Pivot4      while(low<High )5     {6          while(Low//find values smaller than the pivot from the right7--High ;8R[low]=r[high];//cover9          while(Low//look for values larger than the pivot from the leftTen++Low ; OneR[high]=r[low];//cover A     } -A[low]=pivot;//Benchmark record has been last positioned -     returnLow//return high is also possible the}

2. Performance Analysis
The time of fast sorting is mainly spent on the division operation, the interval of length k is divided, the total need k-1 the comparison of the key words.

(1) Worst time complexity
The worst-case scenario is that each time the selected datum is the smallest (or largest) record of the keyword in the current unordered region, the result is that the sub-interval to the left of the Datum is empty (or the right sub-interval is empty), and the number of records in another non-empty sub-interval is divided by only one less than the number of records
Therefore, the fast sorting must do N-1 division, the first Division of the beginning of the interval length of n-i+1, the required number of comparisons is N-i (1≤i≤n-1), the total number of comparisons reached the maximum value:
Cmax= N (n-1)/2=o (n2)
If the partitioning algorithm given above, each time the current unordered area of the 1th record as the benchmark, then when the file's record has been in an ascending order (or descending order), each partition is taken by the baseline is the current unordered region of the minimum (or maximum) of the record, the fast sort will require the most number of comparisons.

(2) Best time complexity
In the best case, the datum for each partition is the "median" record of the current unordered region, and the result is that the length of the two unordered sub-ranges of the datum is roughly equal to the left and right. Total number of keyword comparisons:
0 (NLGN)
Note:
It is easier to use recursive trees to analyze the best case comparisons. Because the left and right sub-interval length is roughly equal after each division, so the height of the recursive tree is O (LGN), and the recursive tree each layer on each node corresponding to the division of the number of key words required in the process of the sum of the total number of keys not more than N, so the overall ordering process required to compare the overall frequency of C (
Because fast-sorting records move no more than the number of comparisons, the worst-case complexity for fast sorting should be 0 (N2) and the best time complexity is O (NLGN).

(3) Selection of benchmark keywords
Selecting the Divided datum keywords in the current unordered area is the key to determining the performance of the algorithm.
   ① The rules of "three taking in"
The "three take in" rule, that is, in the current interval, the first, the end of the interval and the middle position of the keyword comparison, take the values of the three corresponding records as a benchmark, before the beginning of the division of the benchmark record and the 1th record of the area to exchange, thereafter the division process and the above given partition algorithm exactly the same.

  
② random number K (Low≤k≤high) between low and high, using r[k] as the benchmark
The best way to select a datum is to use a random function to generate a random number K (Low≤k≤high) between low and high, using r[k] as the benchmark, which is equivalent to forcing the R[low. The records in high] are randomly distributed. The quick sort obtained by this method is generally called a random quick sort. Specific algorithm "See textbook"
Note:
The fast ordering of randomization is very different from the general fast sorting algorithm. However, after randomization, the performance of the algorithm is greatly improved, especially for the initial order of the file, it is generally not possible to cause the worst case occurrence. The randomization of the algorithm is not only suitable for fast sequencing, but also for other algorithms that require random distribution of data.

(4) Average time complexity
Although the worst time for fast sorting is O (N2), in terms of average performance, it is the fastest in the internal sorting algorithm based on the keyword comparison, and hence the name of the fast sort. Its average time complexity is O (NLGN).

(5) Complexity of space
Quick sort requires a stack within the system to implement recursion. If each partition is more uniform, the height of its recursive tree is O (LGN), so the stack space after recursion is O (LGN). In the worst case, the height of the recursive tree is O (n), and the required stack space is O (n).

(6) Stability
Fast sequencing is non-stable, for example [2,2, 1].

Quick Sort (QuickSort)

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.