Featured Article

Binary Search Algorithm with Example

William Aug 14, 2026

The proficiency of a programmer is often gauged by their ability to craft efficient algorithms, with the binary search algorithm serving as a foundational example. This algorithm, like its alphabetical namesake, brings order to chaos by dividing and conquering. Let's delve into the realm of binary search, step by step, and write an algorithm that embodies the essence of this approach.

binary search algorithm
binary search algorithm

At its core, the binary search algorithm is designed to find a specific value within a sorted array. It does so by repeatedly dividing the search interval in half. If the value of the search key is less than the item in the middle of the interval, it narrows the interval to the lower half. Otherwise, it narrows the interval to the upper half. This process continues until the value is found or the interval is empty.

What is binary search algorithm?  -GeeksforGeeks
What is binary search algorithm? -GeeksforGeeks

The Binary Search Algorithm: A Deep Dive

The binary search algorithm is a goldmine of learning opportunities, allowing us to explore logic, loops, and even recursion. It's a testament to the power of definiteness, perseverance, and adaptability - values that resonate deeply with anyone interested in computer science and algorithms.

Must Know Algorithms for Coding Interviews
Must Know Algorithms for Coding Interviews

Before we dive into the algorithm, let's ensure we have a solid foundation. We'll be using an example array for our demonstrations: `nums = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]`

Creating the Binary Search Function

Binary Search Explained Visually | DSA Guide for Beginners
Binary Search Explained Visually | DSA Guide for Beginners

To create our binary search algorithm, we'll use a function that takes two parameters: our target number and the array to search within. This function will return the index of the target number if found, or -1 if it's not in the array.

We'll start by defining our function with the necessary parameters. The function will also have an initial variable, `left = 0`, which represents the starting index of our search interval.

Setting the Right Boundary

a notebook with diagrams on how to use the search engine for an interactive learning tool
a notebook with diagrams on how to use the search engine for an interactive learning tool

The next step is to determine the right boundary of our interval. We'll use another variable, `right`, which represents the end index of our search interval. Initially, we'll set `right = len(nums) - 1`.

At this stage, we have everything in place to initiate the main loop of our binary search algorithm. The loop will continue until our search interval is empty, i.e., `left` is still less than or equal to `right`.

Divide and Conquer: The Main Loop

Iterative and Recursive Binary Search Algorithm Implementation in Java
Iterative and Recursive Binary Search Algorithm Implementation in Java

In each iteration of the loop, we'll calculate the mid index using the formula `mid = (left + right) // 2`. This floor division operator ensures that we always get an integer result.

Now, we have the mid index, which divides our search interval into two parts. We'll compare the target number with the middle item of our interval. If they're equal, we've found our target, so we'll return the mid index.

Binary Search Explained 🔍 | DSA Algorithm Guide for Coding Interviews
Binary Search Explained 🔍 | DSA Algorithm Guide for Coding Interviews
How to Implement Binary Search Using Iterative Method
How to Implement Binary Search Using Iterative Method
💜 Linear Search vs Binary Search 🔍
💜 Linear Search vs Binary Search 🔍
Abdul Wahab Junaid is Offensive Security Researcher | Quantum Cryptography Analyst
Abdul Wahab Junaid is Offensive Security Researcher | Quantum Cryptography Analyst
Binary Search Explained Step-by-Step
Binary Search Explained Step-by-Step
Complete Computer Science & Cybersecurity Infographics Bundle
Complete Computer Science & Cybersecurity Infographics Bundle
Convert Text to Binary code!
Convert Text to Binary code!
AP COMPUTER SCIENCE notes on binary search in java learn to code for beginners
AP COMPUTER SCIENCE notes on binary search in java learn to code for beginners
Binary Search Flow Explained 🔍 | Step-by-Step DSA Guide ⚡ | Easy Example
Binary Search Flow Explained 🔍 | Step-by-Step DSA Guide ⚡ | Easy Example
Linear And Binary Search Array in C - Probabu
Linear And Binary Search Array in C - Probabu
30 Days of Java – Day 25 | Linear vs Binary Search Explained for Beginners
30 Days of Java – Day 25 | Linear vs Binary Search Explained for Beginners
BINARY CODE
BINARY CODE
Searching Algorithms in C++ – Linear vs Binary Search
Searching Algorithms in C++ – Linear vs Binary Search
Searching Algorithms Explained 🔍 | Linear vs Binary vs Jump vs Interpolation | DSA Made Easy 🚀
Searching Algorithms Explained 🔍 | Linear vs Binary vs Jump vs Interpolation | DSA Made Easy 🚀
Introduction to Binary Search
Introduction to Binary Search
Binary Coding & Decoding Tricks for Bank Exams | Fast Concept Notes
Binary Coding & Decoding Tricks for Bank Exams | Fast Concept Notes
binary search
binary search
the worksheet is shown with numbers and symbols for each computer system, including two computers
the worksheet is shown with numbers and symbols for each computer system, including two computers
an image of a diagram with arrows pointing to different points and numbers on the same line
an image of a diagram with arrows pointing to different points and numbers on the same line

If the target number is less than the middle item, it means the target is in the lower half of the interval. So, we'll update our search interval by setting `right = mid - 1`.

On the other hand, if the target number is greater than the middle item, the target is in the upper half of the interval. So, we'll update our search interval by setting `left = mid + 1`.

Implementing the Binary Search Algorithm

Now that we have a solid understanding of how the binary search algorithm works, let's write the code and see it in action. We'll use a structured programming approach, defining our function first and then testing it with some examples.

Here's a Python implementation of the binary search algorithm:

```python def binary_search(nums, target): left, right = 0, len(nums) - 1 while left <= right: mid = (left + right) // 2 if nums[mid] == target: return mid elif nums[mid] < target: left = mid + 1 else: right = mid - 1 return -1 ```

Testing the Binary Search Function

Now, let's test our function with some examples. We'll use our predefined array `nums = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]` and search for some numbers within it.

The expected output is: `[0, 1, 3, 4, 6, 7, 8, 9, -1]`

Improving Efficiency: Using while True and Conditional Break

An alternative approach to writing the binary search algorithm is to use a `while True` loop with a `break` statement to exit the loop once the target number has been found. This way, we don't need to create a separate condition to check if the target is in the array.

Here's an example of how you can implement this approach in Python:

```python def binary_search_improved(nums, target): left, right = 0, len(nums) - 1 while True: mid = (left + right) // 2 if nums[mid] == target: return mid elif nums[mid] < target: left = mid + 1 else: right = mid - 1 if left > right: return -1 # target is not in the array ```

This implementation provides an elegant solution that eliminates the need for an additional condition to check if the target is in the array. However, it's important to note that it's not strictly more efficient than our initial implementation.

And there you have it - a comprehensive exploration of the binary search algorithm, complete with examples and alternative implementations. This algorithm serves as a cornerstone in computer science, demonstrating the power of logical thinking and efficient coding. It's a testament to the fact that even the most complex problems can be tackled by breaking them down into smaller, more manageable parts.

The beauty of the binary search algorithm lies in its simplicity and effectiveness. It's a shining example of how a well-crafted algorithm can significantly improve the efficiency of code. So, the next time you find yourself staring at a seemingly insurmountable mountain of data, remember the wise words of the binary search algorithm: "Divide and conquer."