Junior — Middle
What happens if you try to add an element to a Map that has not been created or initialized?
sobes.tech AI
Answer from AI
Binary search is an algorithm for finding an element in a sorted array. The principle:
- Determine the middle element of the array.
- If the sought element equals the middle, the search is complete.
- If the sought element is less than the middle, continue in the left half.
- If greater, in the right half.
- Repeat the process recursively or iteratively until the element is found or no elements remain.
Example in Python:
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
# Usage
arr = [1, 3, 5, 7, 9]
print(binary_search(arr, 5)) # Outputs index 2
Binary search is efficient because it halves the search area at each step, providing a complexity of O(log n).