How to sort a list in Python

Asked

Viewed 281 times

2

I’m solving a Python exercise that asks me to sort a list of 5 values typed by the user in ascending order, without using the Sort() method. The problem is my code isn’t working as it should. The error that is happening is that instead of printing all the ordered values, it only prints a few. For example, if I type 7, 4, 2, 8, 3 it prints [2, 4, 7, 8, 3]. I wonder where I went wrong. Follow my code:

listaNumeros = []

for i in range(0, 5):
   numero = int(input('Digite um número: '))

if i == 0:
    listaNumeros.append(numero)
else:
    for j in range(0, len(listaNumeros)):
        if numero < listaNumeros[j]:
            listaNumeros.insert(j, numero)
            break
        else:
            if numero > listaNumeros[j]:
                listaNumeros.append(numero)
                break

print(listaNumeros)

1 answer

3


To resolve this issue you can implement the sorting algorithm Bubble Sort.

To implement Bubble Sort on this issue we must:

  1. Capture the values that will mount the list;
  2. Sort these values;
  3. Display the ordered values.

With this logic the code would be:

def bubble_sort(v):
    fim = len(v)
    while fim > 0:
        i = 0
        while i < fim - 1:
            if v[i] > v[i + 1]:
                v[i], v[i + 1] = v[i + 1], v[i]
            i += 1
        fim -= 1
    return v


listaNumeros = list()
for c in range(1, 6):
    listaNumeros.append(int(input(f'Digite o {c}º valor: ')))

print(bubble_sort(listaNumeros))

Note that when we execute this code we must enter each of the 5 values. Then the code will execute the sort.

How this ordination occurs?

The first block while traverse all possible values of list size in descending order. While the list size is greater than zero the 2nd block while scroll through the list v of 0 until the end and the block if exchange the current value for the next one. Next i is incremented and the variable end is decremented.

After sorting, the list will be displayed.

Testing the code

Imagine that we want to sort the following five values; 6, 4, 3, 5 and 8. In this case, we execute the code and type;

6
4
3
5
8

We press Enter and, the exit will be:

[3, 4, 5, 6, 8]
  • Thanks for the help, I studied this code and I was trying to mount the same as yours. It worked well!

  • I just didn’t understand the first while. Why reading has to happen from the end to the beginning of the list?

Browser other questions tagged

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