- Hackr.io Newsletter
- Posts
- Master Binary Search in C (and Python) for Faster Code
Master Binary Search in C (and Python) for Faster Code
Binary Search cuts your search time in half. Literally. Learn how to implement it in both C and Python, and when it’s the right tool for the job.
When you're working with sorted data, linear search is like walking down a hallway checking every door. Binary search? It's like teleporting to the middle and asking: higher or lower?
This week, we're diving into how binary search works, when to use it, and how to implement it in both C and Python. It's a staple in coding interviews, game dev, systems programming, and real-world apps like search engines, databases, and file systems.
How It Works
Binary search divides a sorted list in half, compares your target value with the middle element, and narrows the search range based on the result. This continues until the target is found or the range is empty.
It runs in O(log n) time, dramatically faster than O(n) linear search for large datasets.
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid # Found
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # Not found
Not comfortable with Python? It’s easy to get started. Here’s how to learn Python.
And note how it looks in C:
int binarySearch(int arr[], int size, int target) {
int left = 0, right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2; // avoid overflow
if (arr[mid] == target)
return mid;
else if (arr[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}
Binary search is the fastest way to search sorted data. If your data isn't sorted, sort it first—or use a different approach. For everything from logins to file lookup, binary search is a key part of your algorithm toolkit.
Common Use Cases:
Searching large sorted arrays or lists
Index lookups in databases
Log file analysis
Efficient condition checks (e.g., finding the smallest/biggest index that satisfies a condition)
Real-time applications with strict speed requirements
Partner Message
Find out why 1M+ professionals read Superhuman AI daily.
In 2 years you will be working for AI
Or an AI will be working for you
Here's how you can future-proof yourself:
Join the Superhuman AI newsletter – read by 1M+ people at top companies
Master AI tools, tutorials, and news in just 3 minutes a day
Become 10X more productive using AI
Join 1,000,000+ pros at companies like Google, Meta, and Amazon that are using AI to get ahead.
Rate this NewsletterThe team at Hackr.io aims to provide the best information possible. Please let us know how we're doing! |