在python

时间:2017-11-05 17:36:00

标签: python recursion mergesort

我理解合并排序是如何工作的,但是当我尝试在python中实现时,我认为我仍然对如何在堆栈上实现工作感到困惑。我有一个名为merge_sorted_list的函数,用于合并两个排序列表和一个名为merge_sort1和merge_sort2的函数,这些函数用于递归过程。 " merge_sort1"和" merge_sort2"非常相似,但只有merge_sort2给出了正确的答案。看起来merge_sort1没有在堆栈的每个级别获取返回值。谁能告诉我merge_sort1和merge_sort2之间的评价有什么不同呢?

def merge_sorted_list(list1,list2):

    if(len(list1) == 0 or len(list2) == 0):
        print('input error')
        return;

    i = 0
    j = 0
    k = 0
    list_merge = [0]*(len(list1) + len(list2))
    while(i < len(list1) and j < len(list2)):
        if (list1[i] < list2[j]):
            list_merge[k] = list1[i]
            i += 1
        else:
            list_merge[k] = list2[j]
            j += 1
        k += 1
    while(i < len(list1)):
        list_merge[k] = list1[i]
        i += 1
        k += 1
    while (j < len(list2)):
        list_merge[k] = list2[j]
        j += 1
        k += 1
    return(list_merge)

def merge_sort1(mylist):
    print("splitting ",mylist)
    if (len(mylist) > 1):
        mid = len(mylist)//2
        merge_sort1(mylist[:mid])
        merge_sort1(mylist[mid:])

    #   lefthalf = mylist[:mid]
    #   righthalf = mylist[mid:]

    #   merge_sort1(lefthalf)
    #   merge_sort1(righthalf)

        mylist[:] = merge_sorted_list(mylist[:mid],mylist[mid:])
        print("merging result ",mylist)
    return mylist

def merge_sort2(mylist):
    print("splitting ",mylist)
    if (len(mylist) > 1):

        mid = len(mylist)//2
#       merge_sort2(mylist[:mid])
#       merge_sort2(mylist[mid:])

        lefthalf = mylist[:mid]
        righthalf = mylist[mid:]

        merge_sort2(lefthalf)
        merge_sort2(righthalf)

        mylist[:] = merge_sorted_list(lefthalf,righthalf)
        print("merging result ",mylist)
    return mylist

如果我们尝试merge_sort1([4,67,3,3,2,6]),输出将是

('splitting ', [4, 67, 3, 3, 2, 6])
('splitting ', [4, 67, 3])  
('splitting ', [4])
('splitting ', [67, 3])
('splitting ', [67])
('splitting ', [3])
('merging result ', [3, 67])
('merging result ', [4, 67, 3])
('splitting ', [3, 2, 6])
('splitting ', [3])
('splitting ', [2, 6])
('splitting ', [2])
('splitting ', [6])
('merging result ', [2, 6])
('merging result ', [2, 3, 6])
('merging result ', [3, 2, 4, 6, 67, 3])

merge_sort2([4,67,3,3,2,6])的输出将是

('splitting ', [4, 67, 3, 3, 2, 6])
('splitting ', [4, 67, 3])
('splitting ', [4])
('splitting ', [67, 3])
('splitting ', [67])
('splitting ', [3])
('merging result ', [3, 67])
('merging result ', [3, 4, 67])
('splitting ', [3, 2, 6])
('splitting ', [3])
('splitting ', [2, 6])
('splitting ', [2])
('splitting ', [6])
('merging result ', [2, 6])
('merging result ', [2, 3, 6])
('merging result ', [2, 3, 3, 4, 6, 67])

非常感谢

1 个答案:

答案 0 :(得分:1)

mylist[:mid] 返回列表。在list_sort1中,您(尝试)对此列表进行排序,然后立即将其丢弃。稍后,您正在使用mylist[:mid]的第二个(未修改的)实例。等mylist[mid:]。另一方面,在第二个版本中,您将mylist[:mid]等的结果分配给变量,因此不会丢弃对它们进行排序的结果。