python实现快速排序
2018-07-26 本文已影响0人
阿漠不冷漠
受Haskell的快排启发
qsort :: [Int] -> [Int]
qsort [] = []
qsort (pivot:others) = (qsort lowers) ++ [pivot] ++ (qsort highers)
where lowers = filter (<pivot) others
highers = filter (>=pivot) others
尝试了用python实现:
def qsort(lst):
if not lst:
return []
pivot = lst[0]
sub_lst = lst[1:]
return qsort(lower_elements(pivot, sub_lst))+[pivot]+qsort(highter_elements(pivot, sub_lst))
def lower_elements(pivot,lst):
return [x for x in lst if x < pivot]
def highter_elements(pivot, lst):
return [x for x in lst if x >= pivot]
使用python实现更容易理解了(:зゝ∠)