Learn python for the first time, use python to write fast
1 # -*- coding:utf-8 -*- 2 # @Time :2019/7/7 15:08 3 # @Author :Zeng Ge 4 5 def quick_sort(blist,low,high): 6 if low<high: # When there is only one element, it is no longer recursive 7 # Otherwise, the index will be out of bounds. 8 # In fact, it will cause the problem of too deep recursion, but it will be covered by the index out of bounds. 9 refer = blist[low] 10 i = low 11 j = high 12 while i<j: # Primary subsequence sorting 13 #First move right.,Can't move right first 14 # Such as 54 26 93,,, 20 15 # In this case, the first time you lie down is 54 26 93,,, 93. 16 while i<j and blist[j]>=refer: 17 j-=1 # Location j 18 if i<j: 19 blist[i]=blist[j] 20 i+=1 # Ready to move left to right 21 while i<j and blist[i]<=refer: 22 i+=1 23 if i<j: 24 blist[j]=blist[i] 25 j-=1 26 # After a subsequence sorting 27 blist[i]=refer 28 quick_sort(blist,low,i-1) 29 quick_sort(blist,i+1,high) 30 return blist 31 32 if __name__=="__main__": 33 bl=[54,26,93,17,77,31,44,55,20] 34 high=len(bl)-1 35 print(quick_sort(bl,0,high))
Conclusion: 1. If low < high: statement =, I added this judgment last when writing fast sorting. What I thought at that time was that when the subsequence is an element, there is no need for recursion and assignment. I never considered setting recursion exit from beginning to end (actually writing recursion algorithm, recursion exit is the first thing to be considered).
2. When the left endpoint is selected as the comparison value, the comparison should be started from the right endpoint; otherwise, the comparison should be started from the left endpoint (there are two versions in the quick row, maybe more than two versions, which is the easiest to understand, and the i of this version starts from the subscript 0).
Another version of i starts from 1, and when the comparison value is selected as the left endpoint, it starts from the left; i haven't written about the quick arrangement of this version.
3. The debug function is quite suitable for sorting algorithms. When I debug, I mainly set breakpoints in the print line and quick [sort (blist, low, i-1) line. With step into and step out, I can quickly track the sorting results and variable values of each step. I didn't debug PHP before, but now I find that it's always nice to debug.