I would like to know how to get the value of the amount of commutations in a list sort. without using Sorted()

Asked

Viewed 38 times

-2

s = [2, 4, 3, 1, 6, 7, 5, 8]

for i in range(len(s)):

    for j in range(i+1,len(s)):
        if s[i] > s[j]:
            aux = s[i]
            s[i] = s[j]
            s[j] = aux
            
print(s)
  • 2

    Please give more details about your question. It is also good to use the language tag you are using.

  • 1

    Check out these two links on how to improve your question: https://pt.meta.stackoverflow.com/questions/8089/guia-de-sobreviv%C3%aancia-do-sopt-vers%C3%a3o-curta? cb=1 and https://pt.meta.stackoverflow.com/questions/8388/que-erro-eu-cometi-fazendo-minha-pergunta?cb=1 . Improving the question makes it easier for people to help you.

2 answers

1

Just create a variable to count, and increment it when you have a trade:

s = [2, 4, 3, 1, 6, 7, 5, 8]
cont = 0
for i in range(len(s)):
    for j in range(i+1,len(s)):
        if s[i] > s[j]:
            s[i], s[j] = s[j], s[i]
            cont += 1 # incrementa o contador
            
print(s) # [1, 2, 3, 4, 5, 6, 7, 8]
print(cont) # 6

To another answer suggested to create a function to make the exchange and accounting of the same, but for a simple case like this I find exaggeration. Incrementing the counter in the very place where the change is made seems to me enough.

Also note that the exchange can be made with multiple assignment, without the need for an auxiliary variable.

0

It is only create a counter that will be accounted for only when there is the exchange, it seems to me that the language is python


Whenever there is an exchange it is made and returns 1 otherwise returns 0

def troca(vetor,i,j):
   if vetor[i] > vetor[j]:
        aux = vetor[i]
        vetor[i] = vetor[j]
        vetor[j] = aux
        return 1
   return 0

Vector to be ordered vetor = [2, 4, 3, 1, 6, 7, 5, 8]

Control Variable qtd = 0


Traverse the vector and try to make a change ( only counts if the change has occurred)

for i in range(len(vetor)):
    for j in range(i+1,len(vetor)):
      qtd = qtd + troca(vetor,i,j)

Check the amount of exchanges occurring

print(qtd)

The drawback is to create the control flag and whenever the change occurs to increment it

Browser other questions tagged

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