【问题标题】:Recursion not exiting on the base case in merge sort合并排序中的基本情况下没有退出递归
【发布时间】:2021-08-13 00:38:54
【问题描述】:

我正在学习 python 并正在实现 2D 矩阵合并排序,我的代码在调用合并排序时进入无限循环,我无法找到相同的原因。

def mergesort(arr,l,r,u,d):
    if(l>=r or u>=d):
        return

    else :
        mid_h = l + int((r-1)/2)
        mid_v = u + int((d-1)/2)

        print( l,mid_h)
        print(u,mid_v)

        mergesort(arr,l,mid_h,u,mid_v)
        mergesort(arr,mid_h+1,r,u,mid_v)
        mergesort(arr,l,mid_h,mid_v+1,d)
        mergesort(arr,mid_h+1,r,mid_v+1,d)

        merge_row(arr,l,mid_h,r,u,mid_v,d)
        merge_col(arr,l,mid_h,r,u,mid_v,d)

【问题讨论】:

  • l、r、u、d分别代表左、右、上、下
  • 您能否为arr 提供一个触发无限递归的small 示例值? merge_rowmerge_col 打电话给mergesort 吗?
  • print(l, r, u, d) 放在开头,这样您就可以查看是否总是越来越接近基本情况。
  • 我不明白代码背后的逻辑。你到底是按什么排序的?
  • 如果x == 0x + y/2 只是xy 之间的中点。你想要x + (x - y)/2这样的东西。

标签: python algorithm sorting multidimensional-array


【解决方案1】:

您的中点实际上并不是中点。考虑l == 5r == 8。然后l + r//2 == 5 + 4 == 9

相反,你想要

# Add half the distance between the endpoints, not half the far endpoint.
mid_h = l + (r - l) // 2
mid_v = u + (d - u) // 2

【讨论】:

    猜你喜欢
    • 2014-12-14
    • 1970-01-01
    • 2016-09-01
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 2012-09-16
    • 1970-01-01
    相关资源
    最近更新 更多