Leetcode Tag Search | Back

Merge sort

Category: /template
# sort an array list
def merge(nums):
    if len(nums) < 2: return nums  # handle empty and single item
    pivot = len(nums) // 2
    # actually pivot decides left_lst size is <= right_lst
    left_lst = merge(nums[:pivot])
    right_lst = merge(nums[pivot:])
    return merge_sort(left_lst, right_lst)


def merge_sort(left_lst, right_lst):
    result = []
    lft_idx, rgt_idx = 0, 0
    while lft_idx < len(left_lst) and rgt_idx < len(right_lst):
        if left_lst[lft_idx] < right_lst[rgt_idx]:
            result.append(left_lst[lft_idx])
            lft_idx += 1
        else:
            result.append(right_lst[rgt_idx])
            rgt_idx += 1
    result.extend(left_lst[lft_idx:])
    result.extend(right_lst[rgt_idx:])
    return result

def test_merge():
    nums = [1, 5, 3, 2, 8, 7, 6, 4]
    expect = [1, 2, 3, 4, 5, 6, 7, 8]
    result = merge(nums)
    assert result == expect

if __name__ == "__main__":
    """ run command
    pytest <this file>
    python -m pytest merge_sort_array.py
    """
    import pytest
    pytest.main()

讨论

提示

  • 如果看不到讨论部分, 请暂时关掉adblock in Firefox/Chrome
  • 本网站使用Javascript实现评论功能, 此处外链对提高您的网站PR没有帮助. (潜台词: 请不要灌水, 谢谢)