Fast sorting algorithm, called Fast Row, is the most practical sorting algorithm, not one, the major language standard library of the sorting function is basically based on the implementation of the fast line.
Quick-line basic idea: The basic idea of fast sorting is: The data is divided into two separate parts by a trip sort, and some of them are smaller than all the data in the other part, and then the two parts of the data are sorted quickly by this method, the whole sort process can be recursive. To achieve the entire data into an ordered sequence.
One, the use of recursive way:
defpartition (L,left,right): TMP=L[left] whileleft<Right : whileLeft<right andl[right]>=Tmp:right-=1L[left]=L[right] whileLeft<right andl[left]<=Tmp:left+=1L[right]=L[left] L[left]=tmpreturn LeftdefQuick_sort (l,left,right):ifleft<Right:mid=partition (L,left,right) quick_sort (L,left,mid-1) Quick_sort (L,mid+1, right) L=[i forIinchRange (10000)]random.shuffle (l)Print(L) quick_sort (L,0,len (L)-1)Print(l)
Second, the use of non-recursive way: the use of the idea of the stack
There are two issues to consider:
1) What is stored inside the stack?
2) What are the conditions for the end of the iteration?
-a function parameter that needs to be iterated is stored inside the stack
-The end condition is also related to the parameters that need to be iterated. For a quick sort,
The parameters of the iteration are high at the upper and lower bounds of the array, and the condition for the end of the iteration is low = = high.
defQuick_sort (L, left, right):ifLeft >=Right :returnStack=[] Stack.append (left) stack.append (right) whileStack:low=stack.pop (0) High=stack.pop (0)ifHigh-Low <=0:Continuex=L[high] I= Low-1 forJinchRange (Low, high):ifL[J] <=x:i+ = 1L[i], L[j]=L[j], L[i] l[i+ 1], l[high] = L[high], L[i + 1] Stack.extend ([Low, I, I+ 2, high])
Quick sort: recursive vs. non-recursive