Efficient Search Methods
Binary Search: A Logarithmic Approach
Binary search is a highly efficient search algorithm for sorted lists, reducing time complexity from O(n) to O(log n).
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
## Example usage
sorted_numbers = [1, 3, 5, 7, 9, 11, 13, 15]
result = binary_search(sorted_numbers, 7)
print(f"Index of 7: {result}")
Search Method Comparison
Search Method |
Time Complexity |
Prerequisite |
Best Use Case |
Linear Search |
O(n) |
Unsorted list |
Small lists |
Binary Search |
O(log n) |
Sorted list |
Large sorted lists |
Binary Search Visualization
graph TD
A[Start Search] --> B[Calculate Middle]
B --> C{Compare Target}
C -->|Equal| D[Return Index]
C -->|Less| E[Search Left Half]
C -->|Greater| F[Search Right Half]
E --> B
F --> B
Advanced Search Techniques
Set and Dictionary Lookups
Python provides extremely fast lookup methods using sets and dictionaries.
## Set lookup
numbers_set = {1, 2, 3, 4, 5}
print(7 in numbers_set) ## Fast O(1) lookup
## Dictionary lookup
user_dict = {'alice': 25, 'bob': 30}
print('alice' in user_dict) ## Fast O(1) lookup
- Choose search method based on data structure
- Prefer built-in Python methods for optimization
- Consider data size and sorting status
LabEx Insight
At LabEx, we emphasize understanding these efficient search methods to write high-performance Python code.