Get startedGet started for free

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?

This exercise is part of the course

Data Structures and Algorithms in Python

View Course

Exercise instructions

  • 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.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

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]))
Edit and Run Code