我对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}$