Python for fast sorting
Fast sorting adopts the principle of division and governance. The basic idea is to select a number in the array as the benchmark number (generally the first number in the array). During a sorting process, place all those smaller than the benchmark number on the left side of the benchmark, and those larger than the benchmark number on the right side of the benchmark. After sorting, two arrays and a reference number are obtained. All elements in array 1 are smaller than the reference number, and all elements in array 2 are greater than the reference number, then sort the array 1 and 2 in the same order (recursion) until there is a number left.
The Python code implementation is given below
Def partiton (li, low, high ):
Key = li [low]
While low
While low High-= 1
If low
Li [low], li [high] = li [high], li [low]
While low Low + = 1
If low
Li [high], li [low] = li [low], li [high]
Return low
Def quickSort (li, low, high ):
If low> = high:
Return
Center = partiton (li, low, high)
QuickSort (li, low, center-1)
QuickSort (li, center + 1, high)
Implementation:
There are many ways to implement quick sorting. Here I give a general and understandable low position, where the two high pointers traverse the list from the left and right sides. When a high pointer discovers an element smaller than the reference number, it stops moving. At this time, it begins to move the low pointer. When the low pointer discovers an element larger than the reference number, it stops moving, the two pointers exchange element values, so that the two pointers will encounter each other.
Time Complexity:
The specific running time of quick sorting is closely related to the sorting status of the original list. Theoretically, the time complexity of quick sorting is (nlogn), but if you are lucky, for example, if the initial list is [5, 4, 3, 2, 1], what is the implementation process based on the above method? The implementation process is as follows:
[, 1]-> [, 5]-> [, 5]-> [, 5]-> [, 5]->, 3, 4, 5]
This sorting process is very familiar. It is the same as the simplest implementation process of Bubble sorting. Therefore, the worst case of fast sorting is Bubble sorting, and the time complexity is (n2)
The above implementation is more common. If python is not used, and c ++, java and other programming languages are used for implementation, the code structure will not be too different. I have come up with an implementation method that fits the characteristics of the python syntax and can better demonstrate the idea of fast sorting. The difference is that the method time needs to traverse the list twice in layer recursion, that is, the complexity is (2 nlogn)
def qsort(lst): if not lst: return [] return qsort([i for i in lst[1:] if i < lst[0]]) + [lst[0]] + qsort([i for i in lst[1:] if i > lst[0]])