Fast sorting algorithm and Python implementation

Source: Internet
Author: User

The basic idea of quick sorting is that by dividing the sorted data into two separate parts, one part of all the data is smaller than the other part of the data, and then the two parts of the data are quickly sorted by this method, the whole sort process can be recursive, so as to achieve the whole data into ordered SEQUENCE.

such as sequence [6,8,1,4,3,9], Select 6 as the base number. Scan from right to left, look for a number smaller than the base number of 3, swap 6 and 3 position, [3,8,1,4,6,9], and then scan from left to right, looking for a number larger than the base number of 8, Exchange 6 and 8 position, [3,6,1,4,8,9]. Repeat the process until the number on the left side of the datum is smaller than it is, and the number on the right is Larger. The above method is then recursive to the left and right sequences of the base number Respectively.

The implementation code is as Follows:

1 defparttion (v, left, right):2Key =v[left]3Low = left4High = right5      whileLow <high :6          while(low < High) and(v[high] >=key):7high-= 18v[low] =v[high]9          while(low < High) and(v[low] <=key):TenLow + = 1 onev[high] =v[low] av[low] =Key -     return low - defquicksort (v, left, right): the     ifLeft <right : -p =parttion (v, left, right) -Quicksort (v, left, p-1) -Quicksort (v, p+1, Right) +     returnv -  +s = [6, 8, 1, 4, 3, 9, 5, 4, 11, 2, 2, 15, 6] a Print("before Sort:", S) atS1 = quicksort (s, left = 0, right = Len (s)-1) - Print("after sort:", S1)

Operation Result:

Before Sort: [6, 8, 1, 4, 3, 9, 5, 4, one, 2, 2,, 6]after sort: [1, 2, 2, 3, 4, 4, 5, 6, 6, 8, 9, 11, 15]

Fast sorting algorithm and Python implementation

Related Article

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.