(Python) Sort lists without sort ()

1

How to sort a list without using sort ()? The code below is correct, but the teacher does not want you to use sort (). The code has the following statement: "Make a program that, when filling a list with 8 integers, stores it in ascending order. Show the resulting list each time a value is stored."

lista = []
for x in range(8):
    n = int(input("Digite um número inteiro: "))
    lista.append(n)
    lista.sort()

    print(lista)
    
asked by anonymous 04.11.2017 / 07:12

2 answers

3

A little more solution pythonica from Jose's answer would be:

numeros = []
for _ in range(8):
    numero = int(input("Digite um número: "))
    for chave, valor in enumerate(numeros):
        if numero < valor:
            numeros.insert(chave, numero)
            break
    else:
        numeros.append(numero)
    print("Lista atual:", numeros)

See working at Ideone | Repl.it

Using the else structure of for you can exclude the flag idea by simplifying the code.

It is worth mentioning that, in the worst case, this algorithm will make N comparisons, where N is the current size of the list. For 8 numbers this is not critical, but as that amount increases, it could become a bottleneck in performance. As it is possibly just an exercise to fix repetition and control structures, I believe you do not have to worry about it now, but if it is of interest, study other sorting algorithms and try to implement them in the same way.

This also includes the quoted by Jefferson , where you can try to adapt to 8 numbers:

VisualG - 5 Larger Numbers

    
04.11.2017 / 12:10
1

Let's see ...

You need:

  • receive values to sort into a list
  • such ordering needs to be done as you receive such values
  • You can not use the .sort(...)

Useful information to solve the problem

You should use features that deal with positioning a data in the list at the time of insertion. In this case, the .insert(index, valor) method.

This method, when inserted in the given position, pushes to the right the value that previously was there. Example:

a = [1,2,3,4,5]
a.insert(2, 'oi!')

When you enter 'oi' in position 2 of the a list, we get the following setting for a :

[1,2,'oi',3,4,5]

To effectively create the list in an orderly fashion without the .sort(...) method, you will also need to loop nested (loop ). You may also need a tag variable - a flag , as we call it in the area.

Example of how the code could look:

lista = []
flag = False

for x in range(8):

    tamanho = len(lista)

    n = int(input("Digite um número inteiro: "))

    if( tamanho > 0 ):

        for y in range( tamanho ):

            if ( n <= lista[y] ):

                lista.insert( y, n )

                flag = True

                break

    if((x == 0) or (flag == False)):

        lista.append( n )

    else:

        flag = False

print(lista)

Final considerations

I recommend that you look into the topic ( ordering algorithms ) and try to break the head before simply copying the above code. While learning, it is always good to try hard - but try too hard - to solve the exercises / duties / challenges / etc alone so that you can learn to be self-taught and get used to a new way of thinking will come faster after a while. It will broaden your horizons well and sharpen your mind and prepare you for a time when there will be no teacher and no ready solution!

    
04.11.2017 / 11:28