带有冒泡排序功能的Python错误

时间:2014-10-08 02:15:24

标签: python sorting

由于某些原因,我出错了,我无法弄清楚它有什么问题。

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]

我收到以下错误:

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

1 个答案:

答案 0 :(得分:2)

假设lis是整数列表,pas将是一个整数。 for i in pas:失败,因为单个整数中没有i

冒泡排序通常使用外部循环完成,该循环在有任何更改时进行,内部循环遍历n-1 索引,而不是列表元素。您可以在许多地方找到标准实施,这里是rosetta code one

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