[英]Python error with a bubble sort function
For this function for some reason I get errors, and I can't figure out what's wrong with it. 由于某种原因,由于该功能,我会出错,并且无法弄清楚它出了什么问题。
def bubbleSort(lis):
for pas in lis:
for i in pas:
if lis[i] > lis[i+1]:
lis[i],lis[i+1] = lis[i+1],lis[i]
I get the following errors: 我收到以下错误:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
bubbleSort(hello)
File "C:/Users/albert/Desktop/test.py", line 4, in bubbleSort
for i in pas:
TypeError: 'int' object is not iterable
Assuming lis
is a list of integers, pas
will be a single integer. 假设
lis
是一个整数列表,则pas
将是一个整数。 for i in pas:
fails because there are no i
s in a single integer. for i in pas:
失败,因为单个整数中没有i
。
Bubble sort is typically done with an outer loop that goes while there are any changes, and an inner loop that iterates over n-1
indices , not list elements. 冒泡排序通常是通过在发生任何更改时进行的外部循环以及对
n-1
索引而不是列表元素进行迭代的内部循环来完成的。 You can find a standard implementation in many places, here's the rosetta code one : 您可以在许多地方找到标准实现,这是Rosetta代码1 :
def bubble_sort(seq):
"""Inefficiently sort the mutable sequence (list) in place.
seq MUST BE A MUTABLE SEQUENCE.
As with list.sort() and random.shuffle this does NOT return
"""
changed = True
while changed:
changed = False
for i in xrange(len(seq) - 1):
if seq[i] > seq[i+1]:
seq[i], seq[i+1] = seq[i+1], seq[i]
changed = True
return None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.