रिकर्शन का उपयोग करके बाइनरी सर्च
इस अभ्यास में, आप recursion का उपयोग करके अभी सीखा हुआ binary search एल्गोरिदम इम्प्लीमेंट करेंगे. याद रखें कि एक recursive फंक्शन खुद को ही कॉल करता है.
यह अभ्यास पाठ्यक्रम का हिस्सा है
Python में Data Structures और Algorithms
अभ्यास निर्देश
- बेस केस परिभाषित करें.
- जाँचें कि सर्च वैल्यू मध्य के वैल्यू के बराबर है या नहीं.
- लिस्ट के बाएँ आधे हिस्से पर
binary_search_recursive()फंक्शन को रिकर्सिवली कॉल करें. - लिस्ट के दाएँ आधे हिस्से पर
binary_search_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))