📚 Day 96 of #100DaysOfCode in Python: Mastering Searching Algorithms
2 min readFeb 29, 2024
Welcome to Day 96! Today, we delve deeper into searching algorithms, fundamental tools in computer science that help us retrieve information from data structures efficiently. We’ll explore binary search, understand hash tables, and touch on advanced searching techniques.
1. Binary Search
- Principle: Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item until you’ve narrowed down the possible locations to just one.
- Implementation:
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid
return -1 # Element is not present in the array
- Complexity: O(log n), where n is the number of elements in the array.
2. Hash Tables
- Overview: A hash table is a data structure that implements an associative array, a structure that can map keys to values.
- How it Works: A hash function is used to compute an…