Implementation process of recursive sorting algorithm quick sorting

Quick sort (Insertion Sort) is also a recursive sorting algorithm.

The principle of quick sorting: First, based on any number in the list (generally choose the head or tail), divide the list into left and right sub-lists.

The number of the left sublist is smaller than the base number, and the number of the right sublist is larger than the base number. Then continue to decompose and compare the left sublist and the right sublist in the same way until there is no separation. Finally, connect the left sublist (smaller than the reference number) + reference number + right sublist (larger than the reference number) to obtain an ordered sequence.

Sorting Algorithm

Take the sequence [3,5,8,1,2,9,4,7,6] as an example, the initial sequence of the sequence is shown in the figure above.

The first grouping: Divide the sequence into two groups based on the last element 6. Traverse the sequence from the left and right ends respectively, the points smaller than 6 are on the left, and the points larger than 6 are on the right. First traverse from left to right, and when an element larger than 6 is encountered, put the element on the right. Similarly, when traversing from right to left, elements smaller than 6 are placed on the left. After all elements are traversed, the left array, element 6, and right array are spliced ​​into a new array in order, and the position of element 6 is fixed at this time.

quick sort first group

Recursively process the left sub-sequence: based on the last element 2, points smaller than 2 are placed in the left sub-sequence, and points larger than 2 are placed in the right sub-sequence. After a round of grouping, the position of element 2 has been fixed. Next Continue to call the above process recursively...

quick sort

Recursively process the right sub-sequence: based on the last element 9, the points smaller than 9 are in the left sub-sequence, and the points larger than 9 are divided into one group after a round of grouping in the right sub-sequence [8, 7 ], recursively process [8, 7] again, so far the sorting is complete.

quick sort

The code of the quicksort program quicksort.py is as follows:

def quicksort(ilist):
less = [] # 小于基准元素的放到这个列表中
equal = [] # 等于基准元素的放到这个列表中
greater = [] # 大于基准元素的放到这个列表中
if len(ilist) > 1:
pivot = ilist[len(ilist)-1] # 取数组最后一个元素作为基准元素
for x in ilist:
if x < pivot: # 小于基准元素的放到列表less中
less.append(x)
elif x == pivot: # 等于基准元素的放到这个列表中
equal.append(x)
elif x > pivot: # 大于基准元素的放到列表greater中
greater.append(x)
return quicksort(less)+equal+quicksort(greater) # 将三部分拼接起来
else: # 只有一个元素的时候直接返回
return ilist

Test the quick sort method, the code is as follows:

1679636428183_Figure 3.png

Guess you like

Origin blog.csdn.net/cz_00001/article/details/131857361