Fibonacci Time Complexity (Continued)
Recurrence Relation:
Time Complexity:
where:
Therefore:
where
We take the larger value for upper bound
Array Search Problems
Example Array:
Task: Check if
Linear Search Algorithm
Given: Array
for i = 0 to n-1:
if A[i] == X:
return i // Found at index i
return -1 // Not foundTime Complexity:
Binary Search
Example: If Array sorted:
Finding 20:
- Check mid of array
- Since
: Check left half
Binary Search Algorithm
low = 0
high = n - 1
while (low ≤ high):
mid = (low + high) / 2
if A[mid] == X:
return mid // Found
else if A[mid] > X:
high = mid - 1 // Search left half
else:
low = mid + 1 // Search right half
return -1 // Not foundTime Complexity Analysis:
where
Solving the Recurrence:
Base case:
When
Therefore:
Final Complexity:
Note: Efficient but array must be sorted!