(Python) sort lists without sort()

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 instruction: "make a program that, at the time of filling a list with 8 integers, already stores them incrementally. 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)
Author: Van Scheur Freud Belmont, 2017-11-04

2 answers

A solution a little more pythonica from Joseph'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 on Ideone | Repl.it

Using the else structure of for one can exclude the idea of the flag, simplifying the code.

It is worth noting that in the worst case, this algorithm will make N comparisons, being N the current size of the list. For 8 numbers this is not critical, but the extent that this amount increase, could become a bottleneck in performance. Since it's possibly just an exercise in fixing the repeat and control structures, I believe you don't have to worry about it right now, but if it's of interest, study other ordering algorithms and try to implement them the same way.

This still includes the question cited by Jefferson , where you can try to adapt to 8 numbers:

VisualG - 5 larger numbers

 4
Author: Woss, 2017-11-04 11:10:52

Let's see...

You need:

  • receive values to sort in a list
  • such sorting needs to be done as it receives such values
  • cannot use method .sort(...)

Useful information for troubleshooting

You must use features that deal with placing a data in the list when inserting. In this case, the method .insert(index, valor).

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

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

By entering 'oi' in position 2 of the list a, we get the following setting for a:

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

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

Example of how the code:

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 research on the topic ( sorting algorithms) and try to break your head before simply copying the above code. When learning, it is always good that you try a lot-but try a lot even - to solve the exercises/duties/challenges/etc alone so that you can then learn to be self-taught and get used to a new mode of reasoning that will come more quickly after a while. Go broaden your horizons well and sharpen your mind and prepare you for a time when there will be no teacher nor ready solution!

 1
Author: José, 2017-11-04 10:28:12