(Python) Sort lists without Sort()

Asked

Viewed 17,879 times

2

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, when filling a list with 8 integers, stores them increasingly. 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)
  • Have you studied sorting algorithms?

  • Without using lists, vectors or sort, ordering 8 numbers: https://answall.com/a/240531/64969

  • @Jeffersonquesado this shared question is not equal and the adjunct answer also does not exactly answer Van Sheur’s question. The requested algorithm is one that will sort according to each input.

  • 2

    @Joseph for not being equal I did not suggest duplicate ;-)

  • People,, without need to do the whole exercise right?? #shawled

2 answers

4


A little more solution pythonica of reply from José 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 structure of else of for the idea of flag, simplifying the code.

It is worth noting that, in the worst case, this algorithm will make N comparisons, N being 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. Since it is possibly just an exercise to fix the repetition and control structures, I believe you do not need to worry about it now, but if it is of interest, study other sorting algorithms and try to implement them in the same way.

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

Visualg - 5 larger issues

1

Let’s see...

You need:

  • receive values to sort in a list
  • such ordering needs to be done as you receive such values
  • cannot use the method .sort(...)

Useful information to solve the problem

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

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

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

When inserting 'oi' at position 2 of the list a, we obtain the following configuration for a:

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

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

Example of what the code might look like:

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 researching the subject (sorting algorithms) and try to break your head before simply copying the above code. When learning, it’s good that you try hard - but try hard even - solve the exercises/duties/challenges/etc alone to be able to learn to be self-taught and to get used to a new mode of reasoning that will come more quickly after a while. It will broaden your horizons and sharpen your mind and prepare you for a moment when there will be no teacher and no solution ready!

Browser other questions tagged

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