首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用链接列表进行插入排序

使用链接列表进行插入排序
EN

Stack Overflow用户
提问于 2015-04-02 22:42:54
回答 1查看 2.1K关注 0票数 0

我正在尝试用链接列表创建插入排序。以下是我所拥有的:

代码语言:javascript
复制
def insertion_sort(a):
        """
        -------------------------------------------------------
        Sorts a list using the Insertion Sort algorithm.
        Use: insertion_sort( a )
        -------------------------------------------------------
        Preconditions:
          a - linked list of comparable elements (?)
        Postconditions:
          Contents of a are sorted.
        -------------------------------------------------------
        """        
        unsorted = a._front
        a._front = None

        while unsorted is not None and unsorted._next is not None:
            current = unsorted
            unsorted = unsorted._next

            if current._value < unsorted._value:
                current._next = unsorted._next
                unsorted._next = current
                unsorted = unsorted._next
            else:
                find = unsorted
                while find._next is not None and current._value > find._next._value:
                    find = find._next

                current._next = find._next
                current = find._next
            a._front = unsorted

        return a

我相信我所拥有的在分类上是正确的。然而,当我试图读取主模块中的列表时,我会得到一堆None值。

在这种情况下,插入排序是而不是,在排序时创建一个新列表。相反,它是将所有已排序的元素移至“前线”。

总之,我有两个问题:我不确定插入排序是否正确,而且返回的列表a存在问题,因为它包含None值。提前感谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-03 00:37:32

不完全确定is的类型,但是如果您假设一个简单的:

代码语言:javascript
复制
class Node:
    def __init__(self, value, node=None):
        self._value = value
        self._next = node
    def __str__(self):
        return "Node({}, {})".format(self._value, self._next)

然后插入排序就不远了,它需要正确地处理头部情况:

代码语言:javascript
复制
def insertion_sort(unsorted):    
    head = None
    while unsorted:
        current = unsorted
        unsorted = unsorted._next
        if not head or current._value < head._value:
            current._next = head;
            head = current;
        else:
            find = head;
            while find and current._value > find._next._value:
                find = find._next
            current._next = find._next
            find._next = current
    return head

>>> print(insertion_sort(Node(4, Node(1, Node(3, Node(2))))))
Node(1, Node(2, Node(3, Node(4, None))))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29423690

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档