Home > Software engineering >  the first name appears before the last name in this List. I want to sort the list in alphabetical or
the first name appears before the last name in this List. I want to sort the list in alphabetical or

Time:10-29

I would like to compare every lastname in list in def cmp_names(name1, name2):

def bubble_sort(L, func):
    end = len(L)
    for i in range(end-1):
        for j in range(end-1-i):
            i1 = (end-1) - (j 1)
            i2 = (end-1) - j
            if func(L[i1], L[i2]):
                L[i1],L[i2] = L[i2],L[i1]
    return L


def cmp_names(name1, name2):
    N = []
    for name in N:
        name = name.split(" ")
        firsname = name[0]
        lastname = name[1]
        
        if name1.lastname == name2.lastname:
            name1 = name1.firsname > name2.firsname
            return name1
        else:
            name2 = name1.lastname < name2.lastname
            return name2
    return name1, name2

def main():
    N = ["Chris Terman","Daseong Han","Tom Grimson","Eric Herman","Joseph Shin", "John Brady"]
    N = bubble_sort(N, cmp_names)
    print(N)

main()

the result of this List will sort by last name ["John Brady","Tom Grimson","Daseong Han","Eric Herman","Joseph Shin","Chris Terman"]

CodePudding user response:

For bubble sort you the easiest way is to keep iterating until there are 0 swaps. So using a while loop and iterating over the length of the list and incrementing the swap counter each time you make a swap.

def bubble_sort(L, func):
    while True:
        swaps = 0
        for i in range(1, len(L)):
            if func(L[i-1], L[i]):
                L[i-1],L[i] = L[i],L[i-1]
                swaps  = 1
        if swaps == 0:
            break 
    return L

Then for your compare function all you need to do is compare the last names. So simply split each name and compare them to each other.

For example:

def cmp_names(name1, name2) -> bool:
    return name1.split(' ')[1] > name2.split(' ')[1]

Output:

['John Brady', 'Tom Grimson', 'Daseong Han', 'Eric Herman', 'Joseph Shin', 'Chris Terman']

Of course you could avoid all of the and just use the sorted function:

print(sorted(N, key=lambda x: x.split(' ')[1]))
  • Related