Search code examples
pythonlistsortingbubble-sort

List sorting with bubble sort (list of list)


I have this assignement where I had to put a text file into a list so it looks like this eventually:

[["Afghanistan",647500.0,25500100],["Albania",28748.0,2821977],...,["Zimbabwe",390580.0,12973808]]

So a list of lists which is defined by the function readcountries() I would like to sort this list with a bubble sort (this is required by the assignement) based on one of the parameters in the list of lists (namely the population which is the second number after the country name).

This is what I have so far

def bubblesort():
    Countries = readcountries()
    for i in range(0,len(Countries)):
        madeSwap = False
        for j in range (0,len(Countries)-(i+1)):
            if Countries[j][2] > Countries[j+1][2]:
                temp = Countries[j+1]
                Countries[j+1][2] = Countries[j][2]
                Countries[j] = temp
                madeSwap = True
            if not madeSwap:
                return

But I dont get any kind of sorting with this for some reason and I even have trouble seeing the sorted list after. Any help is welcome


Solution

  • Problem is here Countries[j+1][2] = Countries[j][2] you have to replace with Countries[j+1] = Countries[j]

    Also

    you have to invoke this

    if not madeSwap:
                    return
    

    In outer for

    And return list

    def bubblesort():
            Countries = [["Afghanistan",647500.0,3],["Albania",28748.0,1],["Zimbabwe",390580.0,2]]
            for i in range(0,len(Countries)):
                madeSwap = False
                for j in range (0,len(Countries)-(i+1)):
                    if Countries[j][2] > Countries[j+1][2]:
                        temp = Countries[j+1]
                        Countries[j+1] = Countries[j]
                        Countries[j] = temp
                        madeSwap = True
                if not madeSwap:
                    return Countries
            return Countries
    
    >>> bubblesort()
    [['Afghanistan', 647500.0, 1], ['Zimbabwe', 390580.0, 2], ['Albania', 28748.0, 3]]