Search code examples
pythonlistsortingbubble-sort

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 !


Solution

  • 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']]