Sort with Selection Sort by size and alphabetically

Asked

Viewed 34 times

4

I have a college exercise, but I need some help. I need to do a program that gets a list containing N nomes and returns a list of all received names sorted by size (number of letters) the Selection Sort. In case you have two nomes of the same size, the ordering of these two should be alphabetical increasing. I cannot use the function sort.

I did the first part of sorting by the size of the string:

def nome_ordena(nomes):
    for i in range(len(nomes)):
        i_menor = i
        for j in range(i+1, len(nomes)):
            if len(nomes[i_menor]) > len(nomes[j]):
                i_menor= j  
        nomes[i], nomes[i_menor] = nomes[i_menor], nomes[i]           
    return nomes

I have tried in many ways to alphabetize those that are the same size, but I’m not getting it. Can someone help me?

1 answer

4

Simply include an additional check on if:

def nome_ordena(nomes):
    for i in range(len(nomes)):
        i_menor = i
        for j in range(i + 1, len(nomes)):
            # se tamanho é diferente, ou se o tamanho é igual, usa a ordem alfabética
            if ( len(nomes[i_menor]) > len(nomes[j]) ) or ( len(nomes[i_menor]) == len(nomes[j]) and nomes[i_menor] > nomes[j] ):
                i_menor = j
        nomes[i], nomes[i_menor] = nomes[i_menor], nomes[i]           
    return nomes

nomes = ['Agata', 'Bia', 'Ana', 'Carlos', 'Andrea']
print(nome_ordena(nomes)) # ['Ana', 'Bia', 'Agata', 'Andrea', 'Carlos']

I mean, I see if the size of one is bigger than the other, or if the sizes are equal and one string is larger than another. This works because comparisons between strings with operators > and < take into account the lexicographical order of characters.

Remembering that there is difference between upper and lower case, and also between accented letters:

nomes = ['Agata', 'Ágata', 'agata']
print(nome_ordena(nomes)) # ['Agata', 'agata', 'Ágata']

Browser other questions tagged

You are not signed in. Login or sign up in order to post.