Quick sorting-[Introduction to algorithms]

Source: Internet
Author: User

For an input array containing n numbers,Quick sortingIs the worst case where the time complexity isO (n2). Although the time complexity in the worst case is very poor, fast sorting is usually the best choice in actual sorting applications, because its average performance is very good: its expected time complexity isO (nlgn)In addition, the constant factor hidden in O (nlgn) is very small. In addition, it can sort the original address and even work well in the virtual storage environment.

Used for quick sortingSub-GovernanceIdea:

Decomposition: Convert the ArrayA [low... high]Divided into two subarraysA [low .. mid-1]AndA [mid + 1 .. high],MakeA [low .. mid-1]The element in the sub-array is smaller than A [mid ],A [mid + 1 .. high]If all elements are greater than the [mid] element, the mid position is returned;

Solution: Uses recursive calling to quickly sort sub-arrays;

Merge: Because the sub-array is sorted by the original address, it does not need to be merged: The array is already ordered.

WhereDecomposition:

ProceedOriginal address Rearrangement:

For exampleA [] = {2, 8, 7, 1, 3, 5, 6, 4}For quick sorting;

Perform original address rearrangement in Partition:

Take the last elementX = 4,Light grayPart is <= x,Dark grayThe part is> x; The first round of sorting ends here;

Continue runningQuickSortUntil p> = r (that is, low> = high );

Code:

# Include
 
  
# Include
  
   
# Include
   
    
Using namespace std; void swap (int & m, int & n) // exchange {int temp = m; m = n; n = temp;} int Partition (int *, int low, int high) {int I = low-1; int low = A [high]; // The last element serves as the base point for (int j = low; j 
  
 

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.