Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge Sort 的迭代终止条件 #27

Open
jiaming-cs opened this issue Dec 7, 2020 · 2 comments
Open

Merge Sort 的迭代终止条件 #27

jiaming-cs opened this issue Dec 7, 2020 · 2 comments

Comments

@jiaming-cs
Copy link

感谢您的代码,很简洁,对我准备面试非常受用!

但是我发现merge_sort的终止条件应该为if len(lst) <= 1 而不是if not lst,否则程序会无限递归。

def merge_sort(lst):
    if len(lst) <= 1:
        return lst
    mid = len(lst) // 2
    left = merge_sort(lst[:mid])
    right = merge_sort(lst[mid:])
    return merge(left, right)

def merge(left, right):
    l, r, res = 0, 0, []
    while l < len(left) and r < len(right):
        if left[l] < right[r]:
            res.append(left[l])
            l += 1
        else:
            res.append(right[r])
            r += 1
    return res + left[l:] + right[r:]
@wolverinn
Copy link
Owner

没毛病!感谢!你要不直接提个pull request吧

@jiaming-cs
Copy link
Author

没毛病!感谢!你要不直接提个pull request吧

提交才发现原来是另一个repo,闹笑话了哈哈

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants