Python: An Example of fast sorting (the idea of a binary method) and a python binary method
This article introduces an example of how to implement fast sorting in python (the idea of the binary method) and shares it with you as follows:
Implementation
Store the required numbers in a list.
1. First, set the number on the left to the reference number, and set the index to 0 in the list.
2. Set two moving bits (for comparison) to the leftmost and rightmost, respectively.
3. Then the rightmost person moves to the left to find the one smaller than the base number, and the rightmost person moves from left to right to find the one larger than the base number.
4. After that, replace the two corresponding numbers and continue with Step 3 until the two moving bits meet and replace the benchmark with the one that meets.
5. Finally, split the list into two parts based on the benchmark number. The steps 1-4 on the left and right continue until there is no comparison number (that is, a number.
You will understand:
Implementation Code
# Coding: UTF-8 # Fast sorting. def quick_sort (list, left, right): if left> right: return temp = list [left] I = left j = right while I! = J: # search for the while list [j]> = temp and I from the right to the left <j: j-= 1 # search for the while list [I] <= temp and I <j: I + = 1 if I <j: t = list [I] list [I] = list [j] list [j] = t # Replace the reference number list [left] = list [I] list [I] = temp # recursively call quick_sort (list, left, I-1) quick_sort (list, I + 1, right) while True: list = [] try: num = int (input ('How many do you want to compare? \ N') Before t ValueError: continue for k in range (num): a = int (input ('Enter the number of '+ str (k + 1) +: \ n') list. append (a) quick_sort (list, 0, num-1) print ('sorting result: ') for l in range (len (list): print (list [l], end = '') print ()
Quick sorting is much more efficient than Bubble sorting ~
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.