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:
1 defparttion (v, left, right):2Key =v[left]3Low = left4High = right5 whileLow <high :6 while(low < High) and(v[high] >=key):7high-= 18v[low] =v[high]9 while(low < High) and(v[low] <=key):TenLow + = 1 onev[high] =v[low] av[low] =Key - return low - defquicksort (v, left, right): the ifLeft <right : -p =parttion (v, left, right) -Quicksort (v, left, p-1) -Quicksort (v, p+1, Right) + returnv - +s = [6, 8, 1, 4, 3, 9, 5, 4, 11, 2, 2, 15, 6] a Print("before Sort:", S) atS1 = 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]
Fast sorting algorithm and Python implementation