Search code examples
pythonpython-3.xsortingselection-sort

How to selection sort a tuple in a list so that it sort the tuple in reverse alphabetical order without the use of sorted function


I'm having trouble at sorting a tuple manually so to speak sorting it in reverse alphabetical order without using the sorted() function so far I have done this please feel free to correct me

names = [ ("Yoda", 0.455), ("Abbie", 0.66), ("Gigi", 0.5), ("Xena", 0.12), ("Champ", 0.3) ] 


def sorting_backward(names):
    for i in range(len(names)):
        min = i
        for j in range(i-1,len(names)):
            if names[j] < names[min]:
                min = j
    return names

so I want the output to be: Yoda Xena Gigi Champ

The reason that I want to avoid using the sorted() function is that I want to see if it's possible or not


Solution

  • this will sort it from max to min

    names = [ ("Yoda", 0.455), ("Abbie", 0.66), ("Gigi", 0.5), ("Xena", 0.12), ("Champ", 0.3)]
    sort_list = []
    while names:
        largest = max(names, key=lambda x: x[0])
        print (largest)
        sort_list.append(largest)
        names.pop(names.index(largest))
    
    print(sort_list)