In python Code so far: # TODO: Declare global variables here. recursions = 0 comparisons = 0 def binary_search(nums, target, lower, upper): # Type your code here. target = (lower + upper) //2 global if target == nums[index]: return index if (lower == upper): comparisons +=1 if target == nums[lower]: return lower else: return -1 if (nums[index] < target): recursions += 1 return binary_search(nums,target, index, upper) if nums[index] > target: recursions += 1 return binary_search(nums, target, 0, lower) if __name__ == '__main__': # Input a list of nums from the first line of input nums = [int(n) for n in input().split()] # Input a target value target = int(input()) # Start off with default values: full range of list indices index = binary_search(nums, target, 0, len(nums) - 1) # Output the index where target was found in nums, and the # number of recursions and comparisons performed print(f'index: {index}, recursions: {recursions}, comparisons: {comparisons}')
In python
Code so far:
# TODO: Declare global variables here.
recursions = 0
comparisons = 0
def binary_search(nums, target, lower, upper):
# Type your code here.
target = (lower + upper) //2
global
if target == nums[index]:
return index
if (lower == upper):
comparisons +=1
if target == nums[lower]:
return lower
else:
return -1
if (nums[index] < target):
recursions += 1
return binary_search(nums,target, index, upper)
if nums[index] > target:
recursions += 1
return binary_search(nums, target, 0, lower)
if __name__ == '__main__':
# Input a list of nums from the first line of input
nums = [int(n) for n in input().split()]
# Input a target value
target = int(input())
# Start off with default values: full range of list indices
index = binary_search(nums, target, 0, len(nums) - 1)
# Output the index where target was found in nums, and the
# number of recursions and comparisons performed
print(f'index: {index}, recursions: {recursions}, comparisons: {comparisons}')
Trending now
This is a popular solution!
Step by step
Solved in 3 steps with 1 images