Junior
Which algorithm has a logarithmic complexity of O(log n)?
sobes.tech AI
Answer from AI
The binary (or dichotomous) search algorithm has a logarithmic time complexity of O(log n).
Principle of binary search:
- Requires a sorted array (or list).
- At each step, compares the sought element with the middle element of the current search range.
- If the element matches, the search is complete.
- If the sought element is less than the middle, the search continues in the left half of the range.
- If the sought element is greater than the middle, the search continues in the right half of the range.
- The search range is halved at each step.
Example implementation in Python:
# Binary search function
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
mid_val = arr[mid]
if mid_val == target:
return mid # Element found, return index
elif mid_val < target:
low = mid + 1 # Ignore the left half
else:
high = mid - 1 # Ignore the right half
return -1 # Element not found
# Usage example
# sorted_list = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
# target_value = 23
# result = binary_search(sorted_list, target_value)
# if result != -1:
# print(f"Element found at index: {result}")
# else:
# print("Element not found")
Logarithmic complexity is due to the fact that the number of operations is proportional to the logarithm of the input size (n), since the search space is halved at each step.