简体   繁体   中英

Bubble sort in Python using list of lists not ordering correctly

A bubble sort algorithm in my python program doesn't seem to be finishing the sort or sorting in the correct order.

def sort():
    listsImport()
    for passnum in range(len(numberLists)-1, 0, -1):
        for i in range(passnum):
            if numberLists[i][1] > numberLists[i+1][1]:
                temp = numberLists[i]
                numberLists[i] = numberLists[i+1]
                numberLists[i+1] = temp
    print(numberLists)

Number lists looks like this:
[['hello','5','1'], ['goodbye', '12', '8'], ['salutations', '14,'9']................... ]
It should be sorting by the second elements in the lists.
Thanks !

You need to cast the values to integers:

def sort():
  numberLists = [['hello','5','1'], ['goodbye', '12', '8'], ['salutations', '14','9']]
  for passnum in range(len(numberLists)-1, 0, -1):
     for i in range(passnum):
        if int(numberLists[i][1]) > int(numberLists[i+1][1]):
            temp = numberLists[i]
            numberLists[i] = numberLists[i+1]
            numberLists[i+1] = temp
  return numberLists

Output:

[['hello', '5', '1'], ['goodbye', '12', '8'], ['salutations', '14', '9']]

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