【问题标题】:Python: Merge Sort in ascending and descending orderPython:按升序和降序合并排序
【发布时间】:2018-11-20 11:15:48
【问题描述】:

我正在尝试在 Python 中实现合并排序,根据您给它的参数按升序或降序排序。我让它与 2 个单独的函数一起工作,但我无法让它在一个函数中工作。

def mergeSort(L, ascending = True):
    print('Mergesort, Parameter L:')
    print(L)
    result = []  
    if len(L) == 1:
        return L  
    mid = len(L) // 2  
    teilliste1 = mergeSort(L[:mid], ascending)  
    teilliste2 = mergeSort(L[mid:], ascending)  
    x, y = 0, 0
    while x < len(teilliste1) and y < len(teilliste2):
        if ascending:
            if teilliste1[x] > teilliste2[y]:
                result.append(teilliste2[y])
                y = y + 1
            else:
                result.append(teilliste1[x])
                x = x + 1
        else: 
            if teilliste1[x] < teilliste2[y]:
                result.append(teilliste2[y])
                y = y + 1
            else:
                result.append(teilliste1[x])
                x = x + 1
    result = result + teilliste1[x:]
    result = result + teilliste2[y:]
    return result

mergeSort(list, True) # sort in ascending order
mergeSort(list, False) # sort in descending order

只需在 if 语句中翻转 > 就会使其下降,但如果我尝试在一个函数中同时执行这两种操作,它总是会弄乱我的结果。有什么建议吗?

【问题讨论】:

  • 你尝试了什么?应该不难,但也容易出错。
  • 首先,您当然应该将ascending 参数传递给递归调用。
  • 我只是在 if/else 部分之前放了一个“if升序:”,在 if teilliste1[x]
  • 哦,解决了!我一定完全错过了它。谢谢!嵌套两个 if 语句看起来仍然不是很漂亮。有没有办法让它更具可读性?我会在主帖更新!
  • 我想我会做if (ascending and teilliste1[x] &gt; teilliste2[y]) or (not ascending and teilliste1[x] &lt; teilliste2[y]): 然后只需要一个else 子句。如果这不是时间关键部分,您可以定义一个函数进行比较,然后每次只需提及一次值。

标签: python sorting merge mergesort


【解决方案1】:
def mergeSort(L, ascending = True):
    result = []  
    if len(L) == 1:
        return L  
    mid = len(L) // 2

    teilliste1 = mergeSort(L[:mid])

    teilliste2 = mergeSort(L[mid:])

    x, y = 0, 0
    while x < len(teilliste1) and y < len(teilliste2):
        if teilliste1[x] > teilliste2[y]: # < for descending
            result.append(teilliste2[y])
            y = y + 1

        else:
            result.append(teilliste1[x])
            x = x + 1


    result = result + teilliste1[x:]

    result = result + teilliste2[y:]
    if ascending == True :
        return result
    else:
        result.reverse()
        return result

list=[3,2,4,1,5,9,7,6]
print(list)
print(mergeSort(list, True) )# sort in ascending order

【讨论】:

    猜你喜欢
    • 2012-11-08
    • 2023-03-07
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 2011-08-25
    • 2015-10-09
    • 2023-03-12
    • 2021-01-23
    相关资源
    最近更新 更多