Process Overview
Searching algorithms help us find a specific item in a list. Linear search checks each item one by one. Binary search splits the list in half repeatedly but needs the list to be sorted.
Jump into concepts and practice - no test required
Searching algorithms help us find a specific item in a list. Linear search checks each item one by one. Binary search splits the list in half repeatedly but needs the list to be sorted.
List: [1, 3, 7, 9, 11] Indexes: 0 1 2 3 4 Binary Search Steps: low=0, high=4 mid=2 -> value=7 (target found) Linear Search Steps: Check index 0 -> 1 Check index 1 -> 3 Check index 2 -> 7 (found)
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