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

Binary search โดยใช้ recursion

ในแบบฝึกหัดนี้ จะได้ลองนำอัลกอริทึม binary search ที่เพิ่งเรียนไปมาใช้งานด้วย recursion โดย recursive function คือฟังก์ชันที่เรียกตัวเองซ้ำ

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

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

ดูคอร์ส

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

  • กำหนด base case
  • ตรวจสอบว่าค่าที่ค้นหาตรงกับค่าที่อยู่ตรงกลางหรือไม่
  • เรียกฟังก์ชัน binary_search_recursive() แบบ recursive บนครึ่งซ้ายของลิสต์
  • เรียกฟังก์ชัน binary_search_recursive() แบบ recursive บนครึ่งขวาของลิสต์

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

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

def binary_search_recursive(ordered_list, search_value):
  # Define the base case
  if ____(ordered_list) == 0:
    return False
  else:
    middle = len(ordered_list)//2
    # Check whether the search value equals the value in the middle
    if search_value == ____:
        return True
    elif search_value < ordered_list[middle]:
        # Call recursively with the left half of the list
        return ____(ordered_list[:middle], search_value)
    else:
        # Call recursively with the right half of the list
        return ____
  
print(binary_search_recursive([1,5,8,9,15,20,70,72], 5))
แก้ไขและรันโค้ด