我被要求写一个'in place'Quicksort版本。创建了两个内部函数 - 一个递归函数和一个“就地排序”,它选择随机数据透视表(需要这样的问题),对列表进行排序并在排序后返回数据透视表的索引。quicksort in place performance(python)
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)
问题是运行时间 - 包含100元以上的速度很慢排序
列表。
你有一个想法如何提高“subfunc”算法和我的Quicksort性能?
谢谢!
奥伦
谢谢! 仍然不起作用。我试图交换项目,但它会导致索引错误... – jizanthapus