Binary search लागू करना
इस वीडियो में, आपने linear search और binary search को इम्प्लीमेंट करना सीखा और उनके बीच के फर्क देखे.
इस अभ्यास में, आपको binary_search() फंक्शन इम्प्लीमेंट करना है. क्या आप कर पाएँगे?
यह अभ्यास पाठ्यक्रम का हिस्सा है
Python में Data Structures और Algorithms
अभ्यास निर्देश
- जाँच करें कि search value बीच वाले मान के बराबर है या नहीं.
- जाँच करें कि search value, बीच वाले मान से छोटी है या नहीं.
lastकोmiddleमाइनस वन के मान पर सेट करें.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
def binary_search(ordered_list, search_value):
first = 0
last = len(ordered_list) - 1
while first <= last:
middle = (first + last)//2
# Check whether the search value equals the value in the middle
if ____ == ____:
return True
# Check whether the search value is smaller than the value in the middle
elif ____ < ____:
# Set last to the value of middle minus one
____
else:
first = middle + 1
return False
print(binary_search([1,5,8,9,15,20,70,72], 5))