How does this algorithm look for the smallest value of an array?

Asked

Viewed 49 times

0

I’m starting studies and I’m studying the book I understand the algorithms and in cap 2 I don’t understand this algorithm.

Here in case is to find the lowest value of an element.

def buscaMenor(arr):
    menor = arr[0]
    menor_indice = 0
    for i in range(1, len(arr)):
        if arr[i] < menor:
            menor = arr[i]
            menor_indice = i
        return menor_indice  
    
def ordenacaoporselecao(arr):
    novoArr = []
    for i in range(len(arr)):
        menor = buscaMenor(arr)
        novoArr.append(arr.pop(menor))
    return novoArr

print ordenacaoporselecao([5, 3, 6, 2, 10])

here in my understanding I thought I would order the items.

could help me understand these codes and if you have tips or suggestions to learn the algorithms ?

1 answer

0

Yes, the algorithm is ordering the array. The logic is:

  • Sort function has a for that runs through each position of the original array;
  • For each position is called the searchMenor function that searches for the smallest element;
  • The smallest element is inserted into the new array and removed in the original array;
  • The sort function returns the new ordered array.

To understand this more clearly, you can add comments by displaying the value of each variable or simply debugging the code.

  • Thank you, I thought when you printed it he would order from the smallest to the greatest

Browser other questions tagged

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