開始使用免費開始

修正泡沫排序演算法中的臭蟲

你拿到一個使用 bubble sort(泡沫排序)演算法來排序數字串列的程式。在測試時,你發現程式碼不正確。你能修正這個演算法,讓它能正確運作嗎?

本練習屬於課程

Data Structures and Algorithms in Python

檢視課程

練習說明

  • 修正指派 is_sorted 變數時的錯誤。
  • 修正檢查相鄰值時的錯誤。
  • 修正更新 list_length 變數值時的錯誤。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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]))
編輯並執行程式碼