How to sort elements from a list using Selection Sort?

Asked

Viewed 86 times

0

I implemented Selection Sort to sort the text of a . txt that I made into a list. The problem is that it only orders field 1 and field 3, field 2 it did not order, as seen in the output: 10, 100, 2, 5. Where am I missing? Thanks in advance.

Since this is a college job, I can’t use methods like Sort().

import copy

def acharMenorValor(lista,a):
  menor_valor = lista[0][a]
  menor_index = 0
  for i in range(0,len(lista)):
    if lista[i][a] < menor_valor:
      menor_valor = lista[i][a]
      menor_index = i
  return menor_index


def selectionSort(lista,a):
  novaArray = []
  novaLista = copy.deepcopy(lista)
  for i in range(len(novaLista)):
    menor = acharMenorValor(novaLista,a)
    novaArray.append(tuple(novaLista.pop(menor)))
  print(f"Listagem dos produtos pelo campo: {a+1}")
  for i in range(len(novaArray)):
      print(novaArray[i])
  print("--------------------------------------")


if __name__ == "__main__":
    lista = []
    file = open('trabalho.txt')

    for i in range(4):
        lista.append(file.readline().split())
    print("Listagem de produtos lida do arquivo trabalho.txt")
    for i in range(len(lista)):

        print(tuple(lista[i]))

    print("--------------------------------------")

    #USANDO O SELECTION SORT
    for i in range(len(lista)-1):
        selectionSort(lista,i)

Output:

Listagem de produtos lida do arquivo trabalho.txt
('beringela', '10', '1.99')
('arroz', '5', '4.99')
('peixe', '2', '9.99')
('abacaxi', '100', '3.99')
--------------------------------------
Listagem ordenada dos produtos pelo campo: 1
('abacaxi', '100', '3.99')
('arroz', '5', '4.99')
('beringela', '10', '1.99')
('peixe', '2', '9.99')
--------------------------------------
Listagem ordenada dos produtos pelo campo: 2
('beringela', '10', '1.99')
('abacaxi', '100', '3.99')
('peixe', '2', '9.99')
('arroz', '5', '4.99')
--------------------------------------
Listagem ordenada dos produtos pelo campo: 3
('beringela', '10', '1.99')
('abacaxi', '100', '3.99')
('arroz', '5', '4.99')
('peixe', '2', '9.99')
--------------------------------------

1 answer

0

The problem is that your file has text and not numbers. In the same way that 'B' is greater than 'AA', '2' is also considered larger than '11' if they are being treated as texts.

A simple way to solve is to convert numbers at the time of reading. Instead of reading directly:

for i in range(4):
    lista.append(file.readline().split())

Make the conversion that way:

for i in range(4):
    linha = file.readline().split()
    linha[1] = int(linha[1])
    linha[2] = float(linha[2])
    lista.append(linha)

Browser other questions tagged

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