[Algorithm] Quick sort

In order to find a good job, from the code farmer to the engineer, so let's record the understanding of the algorithm series.

Quick sorting is a sort of exchange sorting. It is a manifestation of the idea of ​​divide and conquer in terms of algorithm design. But compared to the original bubble sort, some optimizations have been made.
For quick sorting, the first understanding is that there is a pivot point (midpoint). On the left of this midpoint element are all smaller elements, on the right of this midpoint element are all larger elements. This is the core idea.

How to achieve it?
First, we want to take the first element as the "midpoint" element.
Then traverse left and right.
Think about three while again.

Note that there are some code tips when traversing here.
Taking iterators i and j,
while i <j,
we first look for a larger one, start traversing from the right, once find a small element (smaller than the "midpoint"), stop and record its position as j.
Then start traversing from the left. Here, you can use <=, as long as it is smaller than the midpoint, continue to move forward until you find a large element (larger than the "midpoint") and stop at its position i.
Here we exchange the corresponding elements of i and j.
Continue the while loop

In this way, a round can be completed, and a round can be completed, that is, the left side of the midpoint is small and the right side is large, and the midpoint position is known as i.
Then use two recursive functions.
quickSort (a, n, L, i-1);
quickSort (a, n, i + 1, R);
you can complete the idea of ​​divide and conquer.
code show as below,

// 快速排序,分治法
void quickSort(int a[],int n,int L,int R)
{
    if(L<R)
    {
        int i=L,j=R;
        int temp = a[L];
        while(i<j)
        {
            while(a[j]>temp&&i<j)
            {
                --j;
            }
            while(a[i]<=temp&&i<j)
            {
                ++i;
            }
            swap(a[i],a[j]);
        }
        swap(a[i],a[L]);
        quickSort(a,n,L,i-1);
        quickSort(a,n,i+1,R);
    }
}

Guess you like

Origin www.cnblogs.com/likeshu/p/12727419.html