เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

เขียนโค้ด Selection Sort

ในวิดีโอที่ผ่านมา คุณได้เรียนรู้อัลกอริทึม selection sort แล้ว

ในแบบฝึกหัดนี้ ให้นำอัลกอริทึมดังกล่าวไปใช้งานโดยเติมโค้ดในฟังก์ชัน selection_sort() ให้สมบูรณ์

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

โครงสร้างข้อมูลและอัลกอริทึมใน Python

ดูคอร์ส

คำแนะนำการฝึกหัด

  • กำหนดค่า lowest ให้เป็นสมาชิกของลิสต์ที่ตำแหน่งอินเด็กซ์ i
  • วนซ้ำในลิสต์อีกครั้งโดยเริ่มจากตำแหน่งถัดไปของตัวแปร i
  • เปรียบเทียบว่าสมาชิกของลิสต์ที่ตำแหน่งอินเด็กซ์ j มีค่าน้อยกว่า lowest หรือไม่

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

def selection_sort(my_list):
  list_length = len(my_list)
  for i in range(list_length - 1):
    # Set lowest to the element of the list located at index i
    lowest = ____
    index = i
    # Iterate again over the list starting on the next position of the i variable
    ____ j in range(____, list_length):
      # Compare whether the element of the list located at index j is smaller than lowest
      if _____:
        index = j
        lowest = my_list[j]
    my_list[i] , my_list[index] = my_list[index] , my_list[i]
  return my_list

my_list = [6, 2, 9, 7, 4, 8] 
selection_sort(my_list)
print(my_list)
แก้ไขและรันโค้ด