Skip to content

Searching Algorithms in Python

--8<: "core-logic/searching-algorithms.md"

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!