Junior
214
Which is faster: linear or logarithmic complexity?
Answer from AI
sobes.tech AI
Logarithmic.
Comparison of complexities:
| Complexity | Description | Example algorithm |
|---|---|---|
| $O(\log n)$ | Execution time grows slowly with increasing $n$. | Binary search |
| $O(n)$ | Execution time grows proportionally with $n$. | Linear scan |
For $ n > 2 $, $ \log n < n $.
Example comparison at $ n = 1000 $:
- $ \log_2 1000 \approx 10 $
- $ 1000 $
# Function with logarithmic complexity (binary search)
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
# Function with linear complexity (linear search)
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1