python 冒泡排序及优化_Python中带优化的冒泡排序

我对Python相当陌生,我将从排序算法、PEP8和Python的Zen开始我的旅程。我刚在CodeReview上写了一篇帖子。我做了修复,我想问一下Optimizing Bubble Sort : Second option。我建议第一个选项是优化冒泡排序,但第二个选项有问题。在维基百科中,这个“允许我们跳过很多元素,结果在最坏的情况下,比较计数提高了大约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

问题是为了实现第二个优化选项,我必须做些什么改变。另外,到目前为止,我还试着表现得像伪代码一样。我的代码不工作(不分类),看起来像:

^{pr2}$

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值