简体   繁体   中英

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. for i in pas: fails because there are no i s in a single integer.

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. You can find a standard implementation in many places, here's the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM