【Python&Sort】QuickSort
Python版的快排,使用递归。
1.设置递归终止条件,当元素个数<1时
2.从列表中pop出一个元素pv
3.列表中的剩余值与pv进行对比,大的放入smaller列表,小的放入larger列表
4.返回qs(smaller)+[pv]+qs(larger)
代码如下:
1 def quicksort(array): 2 smaller=[];larger=[] 3 if len(array)<1: 4 return array 5 pv=array.pop() 6 for num in array: 7 if num>pv: 8 larger.append(num) 9 else: 10 smaller.append(num) 11 return quicksort(smaller)+[pv]+quicksort(larger) 12 13 if __name__=='__main__': 14 numarray=[5,4,3,6,7,2,9,1,2,9] 15 numarray=quicksort(numarray) 16 sarray=['hahahahah','heheheheh','abc','every dog has its lucky day'] 17 sarray=quicksort(sarray) 18 print(numarray,'\n',sarray)