110k views
5 votes
Write a function, binSearch, which takes an array of integers ,

along with n, the number of elements in the array (as a size_t),
and an int to search for (target), and returns the index of the
target

1 Answer

2 votes

Answer:

def binSearch(arr, n, target):

left = 0

right = n - 1

while left <= right:

mid = left + (right - left) // 2

if arr[mid] == target:

return mid

elif arr[mid] < target:

left = mid + 1

else:

right = mid - 1

# If the target is not found, return -1

return -1

User Shericka
by
8.1k points