A quick way to sort python

Source: Internet
Author: User
This article mainly introduced the Python implementation of the fast sorting algorithm, combined with an example of the Python fast sorting principle, implementation methods and related operation skills, the need for friends can refer to the next

This paper describes the fast sorting algorithm implemented by Python. Share to everyone for your reference, as follows:

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:


def parttion (V, left, right):  key = v[left] Low = left high = right and low  < high: while (Low    &L T High) and (V[high] >= key): High      -= 1    V[low] = V[high] While    (Low < High) and (V[low] <= key):      Lo W + = 1    V[high] = V[low]    v[low] = key  return lowdef quicksort (V, left, right): If left < right  :    p = parttion (V, left, right)    quicksort (V, left, p-1)    quicksort (V, p+1, right)  return vs = [6, 8, 1, 4, 3, 9 , 5, 4, one, 2, 2, 6]print ("before sort:", s) S1 = 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]

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.