Quick sort algorithm sort Analysis

Source: Internet
Author: User

Quick sort algorithm sort Analysis

The idea of fast sorting is the idea of divide and control.

Generally, based on the first element of the sequence as the mid benchmark, the elements larger than the mid are placed behind. Elements smaller than mid are placed in front. Then, recursively, all the elements before the mid are treated as a new sequence for the previous operation. The elements after the mid are treated as a new sequence, the result is that the sequence is an element. The sorting is complete.

Of course, the baseline element is not necessarily a 1: first element, you can also choose 2: end element, or 3 intermediate element, 4 to take the middle value of the first, last, and in, 4. Obtain a random number. Of course, if this benchmark is selected, the efficiency of the algorithm will be different. It is best to take an intermediate element after sorting all the elements each time, so that the efficiency of the algorithm is the highest.


Taking the sequence, 38, 27 as an example, the first element is taken as the reference.

After the first division, we can get [, 13] 49 [76 97 65]

Then the first sequence is 27 as the benchmark [13] 27 [38] and the elements following the sequence are 76 as the benchmark to get [65] 76 [97]

In this way, the elements are sorted.

It can be seen that the algorithm is actually very simple. The division and control policies can be implemented using a recursive function,

Void Qsort (int low, int high) {int mid; if (low
 
  
The next step is to divide the data according to the benchmark. In this way

Int Partition (int low, int high) {int I = low, j = high, Partition = num [low]; while (I
   
    
= Rows) j --; if (I
    
     


This enables fast sorting.

#include 
      
       #include 
       
        using namespace std;int num[500];int Partition(int low,int high){    int i = low,j = high,pivot = num[low];    while(i
        
         =pivot)            j--;        if(i
         
          


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.