我不会从下面的快速排序代码中得到输出:
def quick_sort(sequence):
length = len(sequence)
if length<=1:
return sequence
else:
pivot = sequence.pop()
item_greater = []
item_lower = []
for item in sequence:
if item> pivot:
item_greater.append(item)
else:
item_lower.append(item)
print( quick_sort(item_lower) + [pivot] + quick_sort(item_greater))测试快速排序算法:
print(quick_sort([91,45,78,124,174,32,75,69,43,15,2,45,19,66]))发布于 2021-12-10 05:31:19
返回您的值,而不是打印出来:
def quick_sort(sequence):
length = len(sequence)
if length<=1:
return sequence
else: pivot = sequence.pop()
item_greter = []
item_lower = []
for item in sequence:
if item > pivot: item_greter.append(item)
else:
item_lower.append(item)
return quick_sort(item_lower) + [pivot] + quick_sort(item_greter)
print(quick_sort([91,45,78,124,174,32,75,69,43,15,2,45,19,66]))发布于 2021-12-10 07:49:28
这些是主要问题:
None,然后+ [pivot]操作将引发一个错误。之后进行。
没有问题,但"greter“的拼写”更大“
另外,您可以跳过第一个else,因为if块将以return结尾。
更正:
def quick_sort(sequence):
length = len(sequence)
if length <= 1:
return sequence
pivot = sequence.pop()
item_greater = []
item_lower = []
for item in sequence:
if item > pivot:
item_greater.append(item)
else:
item_lower.append(item)
return quick_sort(item_lower) + [pivot] + quick_sort(item_greater)
print(quick_sort([91,45,78,124,174,32,75,69,43,15,2,45,19,66]))结束语
pop:lst = 91,45,78,124,174,32,75,69,43,15,2,45,19,66打印(quick_sort(Lst))打印(Lst)#缺少最后一个元素,并且没有排序
item_greater和item_greater)。相反,这些分区应该通过交换输入列表中的值来形成。在这样的implementation.中不应该有[] (新的空列表)或+ (列表连接)。
本地快速排序算法的正确版本随时可用.有许多可能的变体,取决于枢轴选择。在这个网站上也有几个关于这个主题的问答。例如,见:
https://stackoverflow.com/questions/70300103
复制相似问题