Bubble Sort Algorithm in Python

Asked

Viewed 7,390 times

1

def bubble_sort(lista):
elementos = len(lista)-1
ordenado = False
while not ordenado:
    ordenado = True
    for i in range(elementos):
      if lista[i] > lista[i+1]:
           lista[i], lista[i+1] = lista[i+1],lista[i]
           ordenado = False        
    print(lista)
return lista

Print like this bubble_sort([5, 1, 4, 2])

[1, 5, 4, 2]

[1, 4, 5, 2]

[1, 4, 2, 5]

[1, 2, 4, 5]

should return [1, 2, 4, 5]

He is printing bubble_sort([5, 1, 4, 2])

[1, 4, 2, 5]

[1, 2, 4, 5]

[1, 2, 4, 5]

[1, 2, 4, 5]

1 answer

1


I believe it’s more of an identation error:

That way came out right:

def bubble_sort(lista):
    elementos = len(lista)-1
    ordenado = False
    while not ordenado:
        ordenado = True
        for i in range(elementos):
            if lista[i] > lista[i+1]:
                lista[i], lista[i+1] = lista[i+1],lista[i]
                ordenado = False        
                print(lista)
    return lista

My exit was:

>>> def bubble_sort(lista):
...     elementos = len(lista)-1
...     ordenado = False
...     while not ordenado:
...         ordenado = True
...         for i in range(elementos):
...             if lista[i] > lista[i+1]:
...                 lista[i], lista[i+1] = lista[i+1],lista[i]
...                 ordenado = False        
...                 print(lista)
...     return lista
... 
>>> bubble_sort([5, 1, 4, 2])
[1, 5, 4, 2]
[1, 4, 5, 2]
[1, 4, 2, 5]
[1, 2, 4, 5]
[1, 2, 4, 5]

Note that Python is a language that requires its developer to pay attention to identation. Your possible problem is occurring in the use of the command with possible indentation.

print(list)

  • Thank you, I tested the indentation.

Browser other questions tagged

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