【发布时间】:2017-06-02 04:26:34
【问题描述】:
最近我一直在做 HackerRank 30 天的代码挑战,并使用 Python 解决挑战。但是在第 20 天(关于冒泡排序算法)我无法解决它。这是 Hackerrank 中任务的link,下面是我的代码。
import sys
n = int(raw_input().strip())
a = map(int, raw_input().strip().split(' '))
numSwap = 0
for first in a:
b = a[a.index(first)+1:]
for second in b:
if first > second:
a[a.index(first)] = second
a[a.index(second)] = first
numSwap += 1
firstElement = a[0]
lastElement = a[len(a)-1]
print "Array is sorted in %d swaps\nFirst Element: %s\nLast Element: %d " %(numSwap, firstElement, lastElement)
这段代码的输入是:
3
3 2 1
代码的结果是:
Array is sorted in 3 swaps
First Element: 3
Last Element: 1
预期结果:
Array is sorted in 3 swaps.
First Element: 1
Last Element: 3
问题是为什么它没有像预期的那样工作?代码的哪一部分是错误的?谢谢。
【问题讨论】:
-
不幸的是,交换是错误的部分
标签: python python-2.7 bubble-sort