有人能解释一下python中的快速排序实现吗?
这是我从Python Cookbook(第二版)获得的快速排序实现。第5.11节有人能解释一下python中的快速排序实现吗?,python,list-comprehension,quicksort,Python,List Comprehension,Quicksort,这是我从Python Cookbook(第二版)获得的快速排序实现。第5.11节 def qsort(L): if not L: return L pivot = L[0] def lt(x): return x<pivot def ge(x): return x>=pivot return qsort(filter(lt, L[1:]))+[pivot]+qsort(filter(ge, L[1:])) 顺便说一下,我知道什么是递
def qsort(L):
if not L: return L
pivot = L[0]
def lt(x): return x<pivot
def ge(x): return x>=pivot
return qsort(filter(lt, L[1:]))+[pivot]+qsort(filter(ge, L[1:]))
顺便说一下,我知道什么是递归和快速排序。过滤器接受函数和iterable,并返回iterable元素的列表,这些元素导致函数输出True。所以
返回一个列表,其中包含小于轴的排序元素,然后是轴,然后是大于或等于轴的排序元素。添加了一些注释
def qsort(L):
if not L: return L #stop condition
pivot = L[0] #select a pivot! (the first one in the list)
#create two functions - greater-equal, less-than
def lt(x): return x<pivot
def ge(x): return x>=pivot
#now the magic - split the list via the pivot and quick sort the sub lists
return qsort(filter(lt, L[1:])) + # sort all elements smaller than pivot
[pivot] + #the pivot
qsort(filter(ge, L[1:])) # sort all elements greater-equal then pivot
#the with only filter on L[1:] because we don't want the pivot itself (we found it by using L[0]...)
您想了解过滤器功能。是吗?是的,我想了解这个递归过滤器。你应该加上一个事实,这是一个递归函数。我听了他们的话,他们知道什么是递归,但这可能是一个改进。此代码将一直执行,直到列表中只有一个已排序元素为止?如果不是L:返回L还将验证列表是否为空beginning@minitoto-我想这是停止状态的私人案例
return qsort(filter(lt, L[1:]))+[pivot]+qsort(filter(ge, L[1:]))
def qsort(L):
if not L: return L #stop condition
pivot = L[0] #select a pivot! (the first one in the list)
#create two functions - greater-equal, less-than
def lt(x): return x<pivot
def ge(x): return x>=pivot
#now the magic - split the list via the pivot and quick sort the sub lists
return qsort(filter(lt, L[1:])) + # sort all elements smaller than pivot
[pivot] + #the pivot
qsort(filter(ge, L[1:])) # sort all elements greater-equal then pivot
#the with only filter on L[1:] because we don't want the pivot itself (we found it by using L[0]...)