SwadhyAI Notes

All Python notes

Python Search Algorithms 🔍

Searching

Searching algorithms are designed to check for an element or retrieve an element from any data structure where it is stored.

✨ Linear Search

Linear search is a very simple search algorithm. In this type of search, a sequential search is made over all items one by one.

python
def linear_search(arr, x):
    for i in range(len(arr)):
        if arr[i] == x:
            return i
    return -1

arr = [10, 20, 80, 30, 60, 50, 110, 100, 130, 170]
x = 110

result = linear_search(arr, x)

if result != -1:
    print("Element is present at index", str(result))
else:
    print("Element is not present in array")

🎮 Interactive Linear Search Demo

ℹ️ Ready to Search!
100
201
802
303
604
505
1106
1007
1308
1709

⚡ Binary Search

Binary Search is a searching algorithm for finding an element's position in a sorted array.

In this approach, the element is always searched in the middle of a portion of an array.

python
def binary_search(arr, low, high, x):
    if high >= low:
        mid = (high + low) // 2
        if arr[mid] == x:
            return mid
        elif arr[mid] > x:
            return binary_search(arr, low, mid - 1, x)
        else:
            return binary_search(arr, mid + 1, high, x)
    else:
        return -1

arr = [2, 3, 4, 10, 40]
x = 10

result = binary_search(arr, 0, len(arr)-1, x)

if result != -1:
    print("Element is present at index", str(result))
else:
    print("Element is not present in array")

💡 Did You Know?

Binary search is much faster than linear search, but the array must be sorted first.