AlgorithmsBeginner

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.

Loading...

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

  • Time Complexity: O(log n) โ€” Because we throw away half of our remaining options at every single step, this algorithm is blazing fast. Even if you have 1 million items, it takes at most 20 steps to find your target! ๐Ÿคฏ
  • Space Complexity: O(1) for the iterative version (using a simple loop), and O(log n) for the recursive version (due to function calls stacking up).
  • 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

    Keywords: python binary search, binary search python, binary search implementation python, binary search algorithm, iterative binary search python, recursive binary search python, python searching algorithms