Binary Search in Python
Learn Binary Search in Python! A super fun and beginner-friendly guide to finding elements in a sorted array blazing fast using iterative and recursive code.
Try it yourself
Run this code directly in your browser. Click "Open in full editor" to experiment further.
Click Run to see output
Or press Ctrl + Enter
How it works
Binary Search is one of the most famous and useful algorithms in computer science! ๐
How It Works
Imagine you are looking for a word in a physical dictionary (remember those? ๐ ). Do you read every single page from A to Z to find your word? Of course not! You open the book roughly in the middle. If your word comes alphabetically before the middle page, you ignore the entire right half of the book and just look in the left half. Then you split that left half in the middle again! ๐
That's exactly what Binary Search does! It's like a superpower for finding things quickly, but there's a catch: *The array must be sorted first.*
1. Find the middle element.
2. If it's your target, you win! ๐
3. If your target is smaller, focus only on the left half.
4. If your target is bigger, focus only on the right half.
5. Repeat until you find it (or run out of elements to check).
Time Complexity
You'll use this all the time in your coding journey. Give the code a run below and see how fast it works!
Related examples
Bubble Sort in Python
Learn the Bubble Sort algorithm in Python! Step-by-step visual explanation with beginner-friendly, optimized Python code.
Two Sum Algorithm in Python
Learn how to solve the classic Two Sum algorithm in Python! An incredibly fun tutorial on using Hash Maps to upgrade your code from slow O(n^2) to blazing fast O(n).
Merge Sort in Python
Learn Merge Sort in Python! A fun, beginner-friendly guide to the Divide and Conquer sorting strategy with guaranteed fast performance.