IniziaInizia gratis

Correcting a bug in the bubble sort algorithm

You have been given a program that sorts a list of numbers using the bubble sort algorithm. While testing it, you realize that the code is not correct. Could you correct the algorithm so that it works correctly?

Questo esercizio fa parte del corso

Data Structures and Algorithms in Python

Visualizza il corso

Istruzioni dell'esercizio

  • Correct the mistake in the assignment of the is_sorted variable.
  • Correct the mistake when checking the adjacent values.
  • Correct the mistake when updating the value for the list_length variable.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

def bubble_sort(my_list):
  list_length = len(my_list)
  # Correct the mistake
  is_sorted = True
  while not is_sorted:
    is_sorted = True
    for i in range(list_length-1):
      # Correct the mistake
      if my_list[i] < my_list[i+1]:
        my_list[i] , my_list[i+1] = my_list[i+1] , my_list[i]
        is_sorted = False
    # Correct the mistake
    list_length += 1
  return my_list

print(bubble_sort([5, 7, 9, 1, 4, 2]))
Modifica ed esegui il codice