【问题标题】:Recursive Merge Sort on linked lists in pythonpython中链表上的递归合并排序
【发布时间】:2015-07-19 16:58:43
【问题描述】:

我想就我正在处理的这个项目向你寻求帮助,我必须编写适用于链表的递归合并排序函数。这就是我到目前为止所拥有的(我没有把整个代码放在这里只是我正在努力的部分)。

    ....
    def merge_sort(self):
        len_list,len_list2= 0, 0
        list=self.head         #first half of linked list
        list2=self.divide()    #function that makes second half of linked list        
        #from imput like z = SortedList([46, 27, 93, 91, 23])
        #i will get list=46->27->93->None
        #           list2=91->23->
        while list is not None:
            len_list+=1
            list=list.next
        while list2 is not None:
            len_list2+=1
            list2=list2.next
        # in len_list,len_list2 i am storing length of these linked lists

        def merge(self,left,right):
            result,i,j=None,0,0
            while (i<len_list) and (j<len_list2):
                if list.data < list2.data:
                    result.append(list.data)  #append is function which appends   
                    list=list.next            #nodes            
                    i+=1
                else:
                    result.append(list2.data)
                    list2=list2.next
                    j+=1
               #some returns should follow but i dont know what to do

我很确定这在很多层面上都是错误的,我只是试图复制列表的合并排序功能并将其转换为链接列表。如果有人可以帮助我如何做到这一点,而无需更改定义的参数 as( def merge_sort(self)) 并向我展示如何递归调用它,我将不胜感激。事先谢谢你。 另外,为了将链表分成两半,我应该使用函数 divide(self) 但如果你知道任何其他方式,请告诉我

【问题讨论】:

    标签: python python-3.x recursion linked-list mergesort


    【解决方案1】:

    通常list.head 的实现是为了返回对列表第一个元素的引用,而不是列表的前半部分。也许执行 list.divide() 来返回拖链列表会更好:

    left_half, right_half = self.divide()
    

    在你的LinkedList 类中,实现__getitem____len__ 方法会更好,也许更pythonic。

    类似:

    def __len__(self):
        return len(self.list)
    
    def __getitem__(self, position):
        return self.list(position)
    

    第一个允许您快速获取长度,第二个允许您切片项目。

    归并排序的基本结构是:

    def merge_sort(list):
        #Check the list doesn't have 1 item
        if len(list) == 1:
           return list
        #Find the middle of the list
        middle = len(list)//2
    
        #Find the left and right halfs via slicing
        left = list(:middle)
        right = list(middle:)
    
        #Recursively sort your lists
        left = merge_sort(left)
        right = merge_sort(right)
    
        #Merge them together  
        return LinkedList(merge(left, right)
    

    【讨论】:

      猜你喜欢
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 2019-01-22
      相关资源
      最近更新 更多