Searching Algorithms in Python
Searching Algorithms in Python is a core Python concept covering searching Algorithms in Python: --8<: "core-logic/searching-algorithms.md" This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.
Searching Algorithms
Searching is the process of finding a specific item in a collection of data.
1. Linear Search
- Logic: Check every item one by one from the beginning until you find the match.
- Best for: Small, unsorted collections.
- Analogy: Looking for a specific shirt in a messy laundry pile.
2. Binary Search
- Logic: Divide and Conquer. Start in the middle. If the target is smaller, look in the left half; if larger, look in the right half. Repeat.
- Prerequisite: The collection MUST be sorted.
- Analogy: Looking for a name in a physical phone book.
Efficiency
Binary Search is significantly faster than Linear Search for large datasets, but the data must be sorted first.
1. Linear Search Implementation
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i # Return the index
return -1 # Not found
numbers = [10, 23, 45, 70, 11, 15]
print(linear_search(numbers, 70)) # 3
2. Binary Search Implementation (Iterative)
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
# MUST be sorted
sorted_numbers = [11, 15, 23, 45, 70, 99]
print(binary_search(sorted_numbers, 70)) # 4
Common Mistake
Forgetting to sort the list before using Binary Search is a classic error. Always check your data first!