您的冒泡排序代码中有一个错误,这意味着它无法正确排序某些(可能是大多数)列表。这与列表中值的数据类型没有任何关系(它与数字列表或字符串列表有相同的问题)。
这是固定代码:
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
unsorted = False # this was moved out of the for loop
for element in range(0,length):
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList # comment this out when you're done testing
unsorted = True # this was moved up from the else block
它适用于数字和字符串,如下所示:
lst = [12, 5, 13, 8, 9, 65]
>>> bubble(lst)
[5, 12, 13, 8, 9, 65]
[5, 12, 8, 13, 9, 65]
[5, 12, 8, 9, 13, 65]
[5, 8, 12, 9, 13, 65]
[5, 8, 9, 12, 13, 65]
>>> lst
[5, 8, 9, 12, 13, 65]
>>> lst = ['a', 'list', 'of', 'words', 'foo', 'bar', 'baz']
>>> bubble(lst)
['a', 'list', 'of', 'foo', 'words', 'bar', 'baz']
['a', 'list', 'of', 'foo', 'bar', 'words', 'baz']
['a', 'list', 'of', 'foo', 'bar', 'baz', 'words']
['a', 'list', 'foo', 'of', 'bar', 'baz', 'words']
['a', 'list', 'foo', 'bar', 'of', 'baz', 'words']
['a', 'list', 'foo', 'bar', 'baz', 'of', 'words']
['a', 'foo', 'list', 'bar', 'baz', 'of', 'words']
['a', 'foo', 'bar', 'list', 'baz', 'of', 'words']
['a', 'foo', 'bar', 'baz', 'list', 'of', 'words']
['a', 'bar', 'foo', 'baz', 'list', 'of', 'words']
['a', 'bar', 'baz', 'foo', 'list', 'of', 'words']
>>> lst
['a', 'bar', 'baz', 'foo', 'list', 'of', 'words']