Check whether the search value equals the value in the middle. Check whether the search value is smaller than the value

动态 未结 0 69
小小草
小小草 LV1 2023年9月23日 23:40 发表
Here's the completed code: ``` 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 search_value == ordered_list[middle]: return True # Check whether the search value is smaller than the value in the middle elif search_value < ordered_list[middle]: # Set last to the value of middle minus one last = middle - 1 else: first = middle + 1 return False print(binary_search([1,5,8,9,15,20,70,72], 5)) ``` The code implements the binary search algorithm to find a value in an ordered list. It starts by setting the first and last indices of the list, and then it enters a loop that continues as long as there are still elements to search. In each iteration, it calculates the middle index of the remaining elements, and then it checks whether the search value equals the value in the middle. If it does, it returns True. Otherwise, it checks whether the search value is smaller than the value in the middle. If it is, it sets the last index to the value of middle minus one, effectively discarding the upper half of the remaining elements. If it isn't, it sets the first index to the value of middle plus one, effectively discarding the lower half of the remaining elements. If the loop completes without finding the search value, it returns False.
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复