Binary Search in C, C++, Java & Python – Code with Explanation & Examples in Short and Simple

   

C Program

#include<stdio.h>

int main() {
    int a[100], n, x, l = 0, r, m;
    scanf("%d%d", &n, &x);
    for(int i = 0; i < n; i++) scanf("%d", &a[i]);
    r = n - 1;
    while (l <= r) {
        m = (l + r) / 2;
        if (a[m] == x) return printf("Found at %d", m), 0;
        if (a[m] < x) l = m + 1;
        else r = m - 1;
    }
    printf("Not Found");
}

C Output

Input:  
5 23  
10 15 23 31 45  

Output:  
Found at 2


C++ Program

#include<iostream>
using namespace std;

int main() {
    int a[100], n, x, l = 0, r, m;
    cin >> n >> x;
    for(int i = 0; i < n; i++) cin >> a[i];
    r = n - 1;
    while (l <= r) {
        m = (l + r) / 2;
        if (a[m] == x) return cout << "Found at " << m, 0;
        if (a[m] < x) l = m + 1;
        else r = m - 1;
    }
    cout << "Not Found";
}

C++ Output

Input:  
6 42  
5 10 17 29 42 50  

Output:  
Found at 4


JAVA Program

import java.util.*;

class B {
    public static void main(String[] a) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(), x = sc.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) arr[i] = sc.nextInt();
        int l = 0, r = n - 1, m;
        while (l <= r) {
            m = (l + r) / 2;
            if (arr[m] == x) { System.out.print("Found at " + m); return; }
            if (arr[m] < x) l = m + 1;
            else r = m - 1;
        }
        System.out.print("Not Found");
    }
}

JAVA Output

Input:  
4 3  
1 2 3 4  

Output:  
Found at 2


Python Program

n, x = map(int, input().split())
a = list(map(int, input().split()))
l, r = 0, n - 1
while l <= r:
    m = (l + r) // 2
    if a[m] == x: print(f"Found at {m}"); break
    elif a[m] < x: l = m + 1
    else: r = m - 1
else: print("Not Found")

Python Output

Input:  
7 8  
1 2 4 6 8 10 13  

Output:  
Found at 4


In-Depth Learning – Entire Concept in Paragraphs
What Is Binary Search?
Binary Search is an extremely efficient algorithm to locate an element in a sorted array repeatedly dividing the search range in half. It removes half the rest of the elements from the search after each comparison. The main point is — it only works if the array is already sorted.

How Binary Search Works
The process:

Initialize two pointers: low = 0, high = n-1.

Find the middle index: mid = (low + high) / 2.

If arr[mid] == key, we’ve found the element.

If arr[mid] < key, search in the right half → low = mid + 1.

If arr[mid] > key, search in the left half → high = mid - 1.

Repeat until low > high.

Example
Let’s search for 8 in:


[1, 2, 4, 6, 8, 10, 13]
Step 1: mid = (0+6)/2 = 3 → arr[3] = 6 < 8 → search right

Step 2: mid = (4+6)/2 = 5 → arr[5] = 10 > 8 → search left

Step 3: mid = (4+4)/2 = 4 → arr[4] = 8 → match found!

It reduces the number of comparisons considerably when compared to linear search.

Real-Life Analogy
Imagine a dictionary: If you wanted to find the word "Tiger", you'd not begin from the first page. You'd turn to the middle, cross-check the word, and then change your direction — left or right — similar to what binary search does. It's quick and skips unnecessary steps.

Why Binary Search Is Significant
Binary search teaches significant concepts such as:

Divide and conquer

Efficient search

Logarithmic time complexity

Which makes it a programming core algorithm utilized in:

Searching in databases

Searching in game maps

Handling sorted datasets in memory

Data science filtering logic

It's also among the most frequently asked interview questions across tech firms — during coding rounds, whiteboard rounds, and online sites like Leetcode, Codeforces, and HackerRank.

Time Complexity
Best Case: O(1) → if the element is in the middle

Average and Worst Case: O(log n) → reduces time significantly even for huge arrays

Binary Search is to be used only if data is sorted. Otherwise, you should sort it first, and that may take additional time.

Python-Specific Benefit
Python makes the code easier to understand with while loop and if-elif-else sequence replicating the divide-and-check process. For bigger projects, you can also employ bisect module for native binary search.

SEO-Optimized Natural Paragraph for Ranking
Want to learn binary search efficiently? This tutorial presents to you the neatest and most efficient implementations of binary search in C, C++, Java, and Python. Binary search is among the most basic and efficient search algorithms employed in the search of an item within a sorted list. It minimizes time complexity to O(log n), making it a perfect choice for performance-intensive applications. Whether you're an algorithms student, a novice programmer doing array problems, or a coder looking to prep for coding interviews, it's a necessary skill in your programmer arsenal to know how binary search operates and how to do it in an efficient manner.