Quick-Sort explanation

Source: Internet
Author: User

This image represents a fast-sorting, non-random row method. As you can see, it is the right-most value of the selection region as the partition key.

1. Two while loop two to the middle walk, the end of the arrow ends: The left side is greater than the key value, the right side is less than the key value. (What if it equals?) equals can be considered less than or greater than. This is why fast sequencing is unstable. )

2. Replace the values in both arrows.

3. Repeat step 1. Until the left >= and.

4. A division has been completed at this time. (If this is the first time, the key value is not changed at the very end, the array has been divided into two parts, the front is less than key, and the back is greater than key.) Just like

Of course, the position of the key must also be determined, only need to be more than the first value of the key to swap it OK. Such as

This is a perfect division.

5, left hand recursion, right hand recursion, fix.

The code would look like this:

void swap (int *a, int *b) {    int c = *A;    *a = *b;    *b = c;}   
voidQsortintA[],intLowintHigh ) {    intKey =A[last]; intP1 =Low ; intP2 =High ;  while(P1 <p2) {         while(P1 < P2 && A[p1] <key)++P1;  while(P1 < P2 && A[p2] >key)--P2; Swap (&a[p1],&A[P2]); } Swap (&A[p2],a[high]); Qsort (A,low,p1-1); Qsort (A,p1+1, high);}

Baidu Encyclopedia above a bit around:

voidQsort (intA[],intLowintHigh ) {    if(Low >=High ) {        return; }    intFirst =Low ; intLast =High ; intKey =A[first];  while(First <Last ) {         while(First < last && A[last] >=key)--Last ; A[first]=A[last];  while(First < last && A[first] <=key)++First ; A[last]=A[first]; } A[first]=key; Qsort (A, low, first-1); Qsort (A, first+1, high);}

But the effect is the same.

There will be some random methods behind it.

Quick-Sort explanation

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.