我被要求编写一个“就地”快速排序版本。创建了两个内部函数 - 一个递归函数和一个“就地排序”函数,它选择随机枢轴(需要问题),对列表进行就地排序并在排序后返回枢轴的索引。
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”算法和我的快速排序性能吗?
谢谢!
奥伦