The fast sort is a sort of division Exchange C.r.a.hoare in 1962. It adopts a strategy of divide and conquer, which is often referred to as the Partition method (Divide-and-conquermethod).
1. The basic idea of the divide-and-conquer law
The basic idea of divide-and-conquer method is to decompose the original problem into several minor problems with similar structure and original problem. Recursively solve these child problems, and then combine the solutions of these child problems into the solution of the original problem.
2. The basic idea of fast sequencing
Set the current unordered area to be sorted as R[low ... High], the basic idea of rapid ordering can be described as follows:
(1) Decomposition:
In R[low. High] Select a record as the benchmark (Pivot), which divides the current unordered division into the left and right two smaller sub ranges r[low ... PIVOTPOS-1) and R[pivotpos+1..high], and make the key for all records in the left child interval less than or equal to the datum record (may be recorded as pivot) Keyword Pivot.key, the key for all records in the right child interval is greater than or equal to Pivot.key, while the Datum record pivot is located on the correct location (Pivotpos) and does not need to participate in subsequent sorting.
Attention:
The key to partitioning is to require the location of the base record to be pivotpos. The result of the division can be simply expressed as (note Pivot=r[pivotpos]):
R[low.. Pivotpos-1].keys≤r[pivotpos].key≤r[pivotpos+1..high].keys
Which Low≤pivotpos≤high.
(2) Solution:
The r[low of the left and right sub ranges is quickly sorted by recursive invocation. PIVOTPOS-1] and R[pivotpos+1..high] quick sort.
(3) Combination:
Because when the two recursive calls in the solve step end, the left and right two children are ordered. For quick sorting, the group step does not have to do anything, as a null operation.
Python implementation
principle: start with the initial data, then sort the data so that the left side of the data is less than
The data, on the right, is greater than the data, and then recursively sorts the data on both sides.
#!/usr/bin/env python
#_ *_coding:utf-8_*_
def rand (x):
import Random
if x < 3:
x = 5
if x > 1000:
print "Big Data" return
[]
L = range (1, x)
li = [] while
l:
r = random.randint (0, le N (L)-1)
Li.append (L.pop (R)) return
Li
def quicksort (L, Low, hight):
key = L[low]
while low < hight:
while key <= L[hight] and Low < hight:
hight-= 1
l[low], l[hight] = L[hight], l[low]
while key >= L[low] and Low < hight: low
+ = 1
l[low], l[hight] = L[hight], L[low]
l[hight] = Key
return hight
def m_sort (L, Low, hight):
If low >= hgiht:
return
index = quicksort (l, Low, hight
M_sort (l, Low, Index)
m_sort (L, index+1, hight)
def main ():
L = rand (1500)
M_sort (l, 0, Len ( L)-1)
print L
if __name__ = = ' __main__ ':
Main ()