On the sorting in the autumn strokes (summary of sorting method-------Medium)

Source: Internet
Author: User

Continuation of the autumn strokes in the sorting (sorting method summary-------Previous) (because the space is too large), we continue to learn.

    On the sorting in autumn strokes (summary of the sorting method-------previous article)

On the sorting in the autumn strokes (summary of sorting method-------Medium)

Cond

(Original, forwarding must be noted)

   5. Quick Sort

Quick Sort is often asked in interviews (including various improvement ideas), this sort algorithm can be said to be the most widely used sorting algorithm, is a kind of improvement of bubble sort, each exchange is jumping. It is relatively easy to implement, and it can handle a variety of different input data, and in many cases consumes less resources than other sorting algorithms. Ideally, it uses only a small auxiliary stack, the average time complexity of ordering N data items is O (Nlogn), and its internal loop is small, the disadvantage is an unstable sorting algorithm, in the worst case, the time complexity is O (n^2). In fact, the process is very simple, think about it, so I do not want to elaborate, the plot is more precise than the language, the following gives a round of the plot, and then recursion on both sides of the part can be, the figure is as follows:

            

After partitioning, all data values on the left side of the KEY=32 's final position are less than (or equal to) key, and all data values on the right are greater than (or equal to) key.

The code is as follows:

intPartion (intA[],intLeftintRight//Partitioning Operations{    intLleft = left, Rright = right, key =A[lleft];  while(Lleft <rright) {         while(Lleft < Rright && A[rright] >= key)//find the first one below the key on the right.rright--; A[lleft]=A[rright];  while(Lleft < Rright && A[lleft] <= key)//find the first one on the left that is greater than keylleft++; A[rright]=A[lleft]; } A[lleft]=key; returnLleft;//the final position of key}

    Recursion:

void Qsort (intintint right ) {    if (left >= right)//  Recursive end condition        return;     int index = partion (A, left, right);     1); // recursive key left area    1, right); // recursive key right area }

    Non-recursive:

voidQsortintA[],intLeftintRight ) {Std::stack<int>St; if(Left <Right ) {        intMID =partion (A, left, right); if(Left < mid-1)//to the left border into the stack {st.push; St.push (Mid-1); }        if(Mid +1<right)//to the left border into the stack {St.push (Mid+1);        St.push (right); }         while(!st.empty ())//If the stack is not empty, that is, the sort does not end {intQ =St.top ();            St.pop (); intp =St.top ();            St.pop (); Mid=partion (A, p, q);//Continue dividingif(P < mid-1) {St.push (P); St.push (Mid-1); }            if(Mid +1<q) {St.push (Mid+1);            St.push (q); }        }    }}

in the worst case, if the sequence to be sorted is ordered, the quick sort will degenerate to bubble sort, time complexity to O (n^2), and in the best case, each partitioning process happens to divide the file into two identical parts of equal size, and the time complexity is O (NLOGN).

    

    Improved algorithm :

We also mentioned above that, in the worst case scenario, if the backlog sequence is already in order, the fast-track will become very inefficient. An improved approach is described below:

Improved selection of reference pivot elements :     1, select the random number as the pivot. However, the generation of random numbers itself is a cost that simply reduces the average elapsed time of the remainder of the algorithm. 2, using the left side, the right end and center of the value as a pivot element (that is, the three take in). 3. Pivot each time you select the median in the data set.

Improved Code:

voidExchangeint*a,int*b) {    inttmp; TMP= *A; *a = *b; *b =tmp;}voidCompexch (intAint*b) {    if(*a > *b) Exchange (A, b);}intPartion (intA[],intLeftintRight//Partitioning Operations{    intLleft = left +1, Rright = right-1; intkey; //three methods of taking Chinese law    intMid = (left + right)/2; Compexch (&a[left], &A[mid]); Compexch (&a[left], &A[right]); Compexch (&a[mid], &A[right]); Key=A[mid];  while(Lleft <rright) {         while(Lleft < Rright && A[rright] >= key)//find the first one below the key on the right.rright--; A[lleft]=A[rright];  while(Lleft < Rright && A[lleft] <= key)//find the first one on the left that is greater than keylleft++; A[rright]=A[lleft]; } A[lleft]=key; returnLleft;//the final position of key}voidQuicksortintA[],intLeftintRight//The ordering of small regions is based on the insertion sort method (the order of ordered sequences is more efficient O (N)), the three are taken{    if(left >= right)//Recursive End Condition        return; if(Right-left <=5)//when the area segment length is less than 5 o'clock, insert sort is used instead{insertion (A, right-left+1); return; }    inti; I=partion (A, left, right); Quicksort (A, left, I-1); Quicksort (A, I+1, right);}

Here we continue to consider other aspects of the improvement, when the sequence to be sorted with a large number of repeating elements, the standard of the fast-running and become extremely inefficient (oh, why so many ah, annoying ah ....) )。 Hey, of course, there is a solution, the most intuitive idea is to divide the sequence into three parts (three-way division) instead of two parts, that is, smaller than the partition element, larger than the partition element and the part equal to the partition element.

    The three-way division is only slightly modified under the standard fast line: The elements equal to the dividing elements in the left-hand area are placed on the leftmost part of the sequence, and the elements in the right area that are encountered are placed at the far right of the sequence. Then, when two scanned pointers meet, the positions of the elements equal to the elements in the sequence are precisely positioned. the extra effort for duplicate elements is linearly related to the number of duplicate elements found, even if there are no duplicate elements, and the method has no additional overhead and is good .

    

Code:

voidQuicksortintA[],intLeftintRight//The order of small area is divided into three ways by inserting and sorting .{    if(Left >=Right )return; intLleft = left-1, Rright = right, K, p=left-1, q=Right ; intkey; if(Right-left <=1) {insertion (A, right-left+1); return;//Recursive return criteria    }    intMid = (left + right)/2; Compexch (&a[left], &A[mid]); Compexch (&a[left], &A[right]); Compexch (&a[mid], &A[right]); Key=A[right];  while(true)    {         while(a[++lleft]<key);  while(key< a[--Rright]) {            if(Rright = =Left ) {                 Break; }        }        if(Lleft >=rright) {             Break; } Exchange (&a[lleft], &A[rright]); if(a[lleft]==key) {P++; Exchange (&a[p], &A[lleft]); }        if(a[rright]==key) {Q--; Exchange (&AMP;A[Q], &A[rright]); }} Exchange (&a[lleft], &A[right]); Lleft= Lleft-1; Rright= Lleft +1;  for(k = left; k <= P; k++, lleft--) {Exchange (&a[k], &A[lleft]); }     for(k = right-1; K >= Q; K--, rright++) {Exchange (&a[k], &A[rright]);    } quicksort (A, left, lleft); Quicksort (A, rright, right);}

On the sorting in the autumn strokes (summary of sorting method-------Medium)

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.