Implementation of Quicksort in Python - Concise way

 

Because I am learning Python recently, this is the first small example I started to learn. I followed this code and rewritten it with my own ideas, and it can also be used as an initial reference material. If there are new people learning here, you can take a look

Source address: https://www.cnblogs.com/yekwol/p/5778040.html

 

 

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

Such as the sequence [6, 8, 1, 4, 3, 9], choose 6 as the reference number. Scan from right to left, looking for a number smaller than the reference number to be 3, swap the positions of 6 and 3, [3, 8, 1, 4, 6, 9], then scan from left to right, looking for a number larger than the reference number The number is 8, swap the positions of 6 and 8, [3, 6, 1, 4, 8, 9]. Repeat the above process until the numbers to the left of the base number are smaller and the numbers to the right are larger. The above method is then recursively performed on the sequences to the left and right of the reference number, respectively.

The implementation code is as follows:

copy code
1 def parttion(v, left, right):
 2     key = v[left]
 3     low = left
 4     high = right
 5     while low < high:
 6         while (low < high) and (v[high] >= key):
 7             high -= 1
 8         v[low] = v[high]
 9         while (low < high) and (v[low] <= key):
10             low += 1
11         v[high] = v[low]
12         v[low] = key
13     return low
14 def quicksort(v, left, right):
15     if left < right:
16         p = parttion(v, left, right)
17         quicksort(v, left, p-1)
18         quicksort(v, p+1, right)
19     return v
20
21 s = [6, 8, 1, 4, 3, 9, 5, 4, 11, 2, 2, 15, 6]
22 print("before sort:",s)
23 s1 = quicksort(s, left = 0, right = len(s) - 1)
24 print("after sort:",s1)
copy code

operation result:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325218881&siteId=291194637