Python 优化或调整以下合并排序3方式的实现
我最近一直在玩排序算法,在谈到合并排序算法时,我想尝试使用3个排序列表(而不是2个)实现该算法的合并辅助函数Python 优化或调整以下合并排序3方式的实现,python,algorithm,sorting,Python,Algorithm,Sorting,我最近一直在玩排序算法,在谈到合并排序算法时,我想尝试使用3个排序列表(而不是2个)实现该算法的合并辅助函数我当前的实现是可行的,但我想知道是否有某种方法可以对其进行调整或以不同的方式实现,以使其运行更快 代码如下: def merge_three(l1, l2, l3): """This function returns a sorted list made out of the three given lists. >>> merge_three(
我当前的实现是可行的,但我想知道是否有某种方法可以对其进行调整或以不同的方式实现,以使其运行更快 代码如下:
def merge_three(l1, l2, l3):
"""This function returns a sorted list made out of the three
given lists.
>>> merge_three([9, 29], [1, 7, 15], [8, 17, 21])
[1, 7, 8, 9, 15, 17, 21, 29]
"""
index1, index2, index3 = 0, 0, 0
to_loop = len(l1) + len(l2) + len(l3)
sorted_list = []
i = 0
while i < to_loop:
advance = 0
value = float("inf")
if index1 < len(l1) and l1[index1] <= value:
advance = 1
value = l1[index1]
if index2 < len(l2) and l2[index2] <= value:
advance = 2
value = l2[index2]
if index3 < len(l3) and l3[index3] <= value:
advance = 3
value = l3[index3]
sorted_list.append(value)
if advance == 1:
index1 += 1
elif advance == 2:
index2 += 1
else:
index3 += 1
i += 1
return sorted_list
def merge_三(l1、l2、l3):
“”“此函数返回由三个元素组成的排序列表
给定的列表。
>>>合并三个([9,29],[1,7,15],[8,17,21])
[1, 7, 8, 9, 15, 17, 21, 29]
"""
index1,index2,index3=0,0,0
to_loop=len(l1)+len(l2)+len(l3)
已排序的_列表=[]
i=0
当我 如果index1
一种方法是:
def merge(lists):
result = []
while len(lists):
(index, value) = min(enumerate(i[0] for i in lists), key=lambda x: x[1])
result.append(lists[index].pop(0))
if len(lists[index]) == 0:
lists.pop(index)
return result
如果您有可用的代码并且正在寻求改进,那么最好的发布位置是:最快的方式可能是返回排序(l1+l2+l3)
。实际的Python代码的速度大约是其他语言中编译代码的50倍,因此最好尽可能多地使用库函数,因为它们是编译代码。