气泡排序和Python优化

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

标签: python algorithm sorting

我是Python的新手,我从排序算法,PEP8和Python Zen开始了我的旅程。我刚刚在CodeReview上写了一篇文章。我进行了修复,我想问一下Optimizing Bubble Sort : Second option。我实现了优化气泡排序的第一个选项,但是第二个选项却有问题。在Wikipedia中,它“使我们可以跳过很多元素,在最坏的情况下,可以使比较计数提高50%”。因此,我的第一个选项代码如下所示:

def bubble_sort(container):
    """
        Bubble sort with optimization.

        Description
        ----------
        Performance cases:
        Worst      : O(n^2)
        Average    : O(n^2)
        Best case  : O(n)

        Parameters
        ----------
        data_container : Mutable structure with comparable objects and structure
                         which has implemented __len__, __getitem__ and __setitem__.

        Returns
        -------
        None

        Examples
        ----------
        >>> bubble_sort([7,1,2,6,4,2,3])
        [1, 2, 2, 3, 4, 6, 7]

        >>> bubble_sort(['a', 'c', 'b'])
        ['a', 'b', 'c']

    """

    # setting up variables
    length = len(container)
    changed = True

    while changed:
        changed = False
        for i in range(length - 1):
            if container[i] > container[i + 1]:
                container[i], container[i + 1] = container[i + 1], container[i]
                changed = True
        length -= 1

问题是要实现优化的第二个选项,我必须进行哪些更改。另外,到目前为止,我已经尝试过像伪代码一样。我的代码不起作用(没有排序),看起来像:

# setting up variables
length = len(container)

while length >= 1:
    number_of_changed = 0
    for i in range(1, length - 1):
        if container[i-1] > container[i]:
            container[i-1], container[i] = container[i], container[i-1]
            number_of_changed = i
    length = number_of_changed

1 个答案:

答案 0 :(得分:1)

container = [7,1,2,6,4,2,3]
length = len(container)

while length >= 1:
    num = 0
    for i in range(1, length):
        if container[i-1] > container[i]:
            container[i-1], container[i] = container[i], container[i-1]
            num = i
            print(num,'\n')
    length = num
    print(container)

我看到的问题是,您将范围设置为1到(length-1)->(7-1)为6,因此它将转到数组中的第6个元素。因此,从for循环的长度中减去负1即可解决问题。尝试将打印件放置在您认为可能会导致问题的位置,这将帮助您调试程序并告诉您所需的信息。希望这会有所帮助。