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]