此Mergesort算法的返回值应该是多少?

时间:2018-10-30 18:04:12

标签: python-3.x

因此,我试图为8个整数的列表编写基本的mergesort算法。我正在使用2个函数:merge,它将两个列表组合在一起,同时也通过比较对它们进行排序。这可以看作是分而治之的“征服”部分。我的第二个函数称为divide,它使用递归从本质上继续将列表划分为子列表,直到它们成为单个元素为止,然后导致调用merge函数以最终对列表进行排序。我的问题是我不确定divide函数的最终最终返回值的含义或含义是什么?sort('conquering')的所有主要工作都已完成。

我肯定还有一些其他错误可能在某些情况下不起作用,或者可以优化其他功能,但是对所有反馈都表示赞赏。

    def merge(a,b):

      res = []
      #Variables for index of a and b to be compared
      a_ind = 0 
      b_ind = 0
      #Stops when length of res list is == length of a and b merged   
      while len(res) != len(a) + len(b) and a_ind<len(a) and b_ind<len(b):

           if a_ind == len(a) - 1 and b_ind == len(b) - 1:
              res.append(a[a_ind])
              res.append(b[b_ind])
                return res

           if a[a_ind] > b[b_ind]:
              res.append(b[b_ind])
              b_ind += 1
           elif b[b_ind] > a[a_ind]:
              res.append(a[a_ind])
              a_ind += 1
      #THIS IS THE FUNCTION IN WHICHI DO NOT KNOW WHAT TO SET AS THE RETURN VALUE
     def divide(lst):

        if len(lst) <2:

           return lst
        mid = (len(lst))//2
        first = [i for i in lst[0:mid]]
        second = [i for i in lst[mid:]]

        divide(first)
        divide(second)
        merge(first,second)

0 个答案:

没有答案