Sort--Quick Sort

1, cited

  • Bubble sort has its own shortcomings. It is an exchange between two adjacent elements, which is relatively inefficient. It is obviously not good for sorting with more data. Quick sort is an improvement to bubble sort. Proposed by CAR Hoare in 1962.

2. The basic idea

  • The basic idea of ​​quick sort is: divide the data to be sorted into two independent parts by sorting, all the data in one part is smaller than all the data in the other part, and then perform the two parts of data separately according to this method For quick sorting, the entire sorting process can be performed recursively, so that the entire data becomes an ordered sequence.

Consider the following array:
9, 3, 6, 5, 7, 4

first step:

  • First a pivot, this pivot can be chosen at will, you can set an algorithm pivot = array[n/2], take the middle number
    pivot = 5;

The second step:

  • Longer than the pivot left large numbers, find the right number is smaller than the pivot of
    the left to find 9 from the right found 4

third step:

  • Exchange the two numbers found in the second step with
    4 , 3 , 6, 5 , 7, 9

the fourth step:

  • Find the next data that meets the conditions of the second step, until the left and right subscripts are equal, and the current round of exchange ends.
    After a round of exchange:
    4 , 3, 5, 6 , 7, 9

the fifth step:

  • After the fourth step is completed, the data on the left subscript to the left is smaller than the pivot, and the data on the right is larger than the pivot, thus dividing an unordered array into two parts.
    – 4, 3, 5, the data on this side are all smaller than 5 (equal to);
    – 6, 7, 9, the data on this side are all larger than 5;

The sixth step:

  • Start again from the first step to the two parts of the division, recursively call.

3. C language implementation

void quick_sort( int *array, int n)
{
    int left, right, pivot, tmp;
    if (n < 2)  return; //递归退出的条件

    pivot = array[n / 2]; //取中间的数为基准

    for ( left = 0, right = n -1;; left++, right--)
    {
        //从左边开始找大于pivot的数
        while (array[left] < pivot) 
            left++;

        //从右边开始找小于pivot的数
        while (pivot < array[right])
            right--;

        if ( left >= right) //本轮交换结束了
            break;

        //交换
        tmp = array[left];
        array[left] = array[right];
        array[right] = tmp;
    }

    quick_sort(array, left); //对左边的排序
    quick_sort(array + left, n - left);//对右边的排序
}

4. Summary

  1. Divide and conquer
  2. Recursion
  3. exchange

5. Reference

https://www.youtube.com/watch?v=SLauY6PpjW4
http://developer.51cto.com/art/201403/430986.htmyc

Guess you like

Origin blog.csdn.net/amwha/article/details/77440464