就地快速排序性能(python)
我被要求写一个“就地”快速排序版本。创建了两个内部函数-递归函数和“就地排序”函数,用于选择随机轴(这是一个必需的问题),就地对列表进行排序,并在排序后返回轴的索引就地快速排序性能(python),python,performance,quicksort,in-place,Python,Performance,Quicksort,In Place,我被要求写一个“就地”快速排序版本。创建了两个内部函数-递归函数和“就地排序”函数,用于选择随机轴(这是一个必需的问题),就地对列表进行排序,并在排序后返回轴的索引 import random def quicksort(lst): def innerfunc(lst, start=0, end=(len(lst) - 1)): temporal_pivot = subfunc(lst, start, end) if (end - s
import random
def quicksort(lst):
def innerfunc(lst, start=0, end=(len(lst) - 1)):
temporal_pivot = subfunc(lst, start, end)
if (end - start > 1):
if (temporal_pivot == start or temporal_pivot == start + 1):
innerfunc(lst, temporal_pivot + 1, end)
elif (temporal_pivot == end or temporal_pivot == end - 1):
innerfunc(lst, 0 , temporal_pivot - 1)
else:
innerfunc(lst, 0 , temporal_pivot - 1), innerfunc(lst, temporal_pivot + 1, end)
def subfunc(l, start, end):
i_random = random.randint(start, end) # chooses random index!
l[i_random], l[start] = l[start], l[i_random]
i_pivot = start
pivot = l[start]
i = end
while i > i_pivot:
if l[i] <= pivot:
l.insert(i_pivot, l[i])
i_pivot += 1
l.pop(i + 1)
else:
i = i - 1
return i_pivot
return innerfunc(lst)
随机导入
def快速排序(lst):
def innerfunc(lst,开始=0,结束=(len(lst)-1)):
时间轴=子节点(lst、开始、结束)
如果(结束-开始>1):
如果(时间轴==开始或时间轴==开始+1):
innerfunc(lst,时间轴+1,结束)
elif(时间轴==结束或时间轴==结束-1):
innerfunc(lst,0,时间轴-1)
其他:
innerfunc(lst,0,时间轴-1),innerfunc(lst,时间轴+1,结束)
def辅功能(左、开始、结束):
i_random=random.randint(开始,结束)#选择随机索引!
l[i_random],l[start]=l[start],l[i_random]
i_pivot=开始
枢轴=l[开始]
i=结束
当i>i\u轴时:
若l[i]则子UNC似乎不是有效的-循环并插入到数组部分。
我不是Python程序员,但我建议它可能会导致内存重新分配和O(n)操作成本问题在于重复调用l.insert()
和l.pop()
。每个循环都有O(n)
复杂性,而您希望循环的每个迭代都是O(1)
您需要重新编写函数,使其通过交换元素而不是重复执行插入和删除来工作
您可以在中找到一些伪代码