Count number of comparisons and exchange in a python sorting algorithm

Asked

Viewed 280 times

0

I need to count the number of comparisons and exchange in the following sorting algorithm:

def selecao(lista):
    c1 = c2 = 0
    for i in range(0, (len(lista)-1)):
        mini = i
        c1 += 1
        for j in range(i+1, len(lista)):
            c1 +=1
            if lista[j] < lista[mini]:
               c1 += 1
               c2 += 1
               mini = j

    lista[mini], lista[i] = lista[i],lista[mini]

    return c1, c2

So I’m counting how many times the algorithm goes into a repeat loop, so I don’t know how appropriate it is to count how many comparisons. In addition, I need the function to return the number of exchanges made by the line:

lista[mini], lista[i] = lista[i],lista[mini]

I appreciate any help, I’m new to python

  • Number of comparisons: c2; Number of exchanges made: c1.

1 answer

-1


For the number of comparisons you can use the c2, but don’t use the c1 for the number of exchanges because there are times he will count twice, for that use a variable outside the condition, something like

c1 += 1
Ntrocas += 1
if lista[j] < lista[mini]:...

Browser other questions tagged

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