【问题标题】:Optimizing or tweaking the following implementation for Merge Sort 3 way优化或调整合并排序 3 方式的以下实现
【发布时间】:2020-03-23 07:32:52
【问题描述】:

我最近一直在玩排序算法,在接触合并排序算法时,我想尝试使用 3 个排序列表而不是 2 个排序列表来实现算法的合并辅助函数。

我当前的实现可以,但我想知道是否有某种方法可以对其进行调整或以不同的方式实现以使其运行得更快。

代码如下:

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

谢谢你:)

【问题讨论】:

  • 如果您有工作代码并且正在寻求改进,那么更好的发布位置是:codereview.stackexchange.com
  • 最快的方法可能是return sorted(l1 + l2 + l3)
  • 实际 Python 代码的速度大约是其他语言编译代码的 50 倍,因此最好尽可能使用库函数,因为它们是编译代码。

标签: python algorithm sorting


【解决方案1】:

考虑更通用的合并功能会导致设计更简单。假设您想编写一个函数,该函数接受一个排序列表并合并所有列表。这个想法很简单:找到具有最小元素的列表,将其弹出,将其移动到结果列表,当列表为空时从列表列表中删除一个列表,并迭代直到列表列表本身为空。

一种方法是:

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

【讨论】:

    猜你喜欢
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    相关资源
    最近更新 更多