BaşlayınÜcretsiz Başlayın

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?

Bu egzersiz

Data Structures and Algorithms in Python

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

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

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

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]))
Kodu Düzenle ve Çalıştır