Bubble Sort Algorithm in Python

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 this way 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]

It's printing bubble_sort ([5, 1, 4, 2])

[1, 4, 2, 5]

[1, 2, 4, 5]

[1, 2, 4, 5]

[1, 2, 4, 5]

    
asked by anonymous 19.03.2018 / 14:58

1 answer

1

I think it's one more indentation error:

That's how it 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 output 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]

Keep in mind that Python is a language that demands of your developer attention in the indentation. Your possible problem is occurring in the use of the command with possible indentation.

  

print (list)

    
19.03.2018 / 15:15