【发布时间】:2015-01-17 11:08:58
【问题描述】:
我正在尝试在 python 中使用算法实现冒泡排序代码:
我设法使用 double for 编写了一个代码,它工作正常。
A=[43,21,12,80,3,2,35]
lengthOfList = len(A)
for i in range (lengthOfList):
for k in range(lengthOfList-1, i,-1 ):
if ( A[k - 1]> A[k]):
temp = A[k]
A[k] = A[k-1]
A[k-1] = temp
print A
我现在尝试采用这个算法的登录超过 3 个小时,但是我无法让它工作:
procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
#if this pair is out of order
if A[i-1] > A[i] then
# swap them and remember something changed
swap( A[i-1], A[i] )
swapped = true
end if
end for
until not swapped
end procedure
我有点卡在重复和直到阶段。我知道我必须使用 while,但我无法理解如何使用 while 来实现它
【问题讨论】:
-
Bubble Sort Homework的可能重复
-
结果显然是一样的,但是这些代码没有遵循我要求的算法。我在发帖之前已经检查过了。
-
用
while swapped替换for i in range (lengthOfList):,在swap部分设置为true,在每次迭代时重置 -
要准确复制您发布的算法,您需要一个
do-while循环,即not directly available in Python -
如果来自维基页面,则基于pastebin.com/g3PMXSJA