Introduction
Finding a specific item in a list can be tricky if the list is long. Searching algorithms help us quickly locate what we want without checking every single item blindly.
Jump into concepts and practice - no test required
Imagine looking for a word in a dictionary. You don't check every page from the start. Instead, you open near the middle, see if the word is before or after, then open halfway in that section, repeating until you find the word.
List: [2, 4, 6, 8, 10, 12, 14] Linear Search: Start → 2 → 4 → 6 → 8 → ... until target found Binary Search: Step 1: Check middle (8) Step 2: Target < 8? Search left half [2,4,6] Step 3: Check middle (4) Step 4: Target > 4? Search right half [6] Step 5: Check 6 → Found or not
linear search?target in arr?def binary_search(arr, target):
low, high = 0, 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
arr = [2, 4, 6, 8, 10]
print(binary_search(arr, 6))def binary_search(arr, target):
low, high = 0, len(arr)
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