Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 53

Binary Search Program in Java

In this lesson: Binary search program in Java — iterative logic, dry run, complexity and output. Copy & run now. In Hindi & English.

What is binary search

Binary search is a fast way to find a value in a sorted array. Instead of checking every item, it looks at the middle, then throws away the half that cannot contain the target. Repeating this halving finds the item in very few steps.

💡 Binary search only works on a sorted array — it decides which half to keep from the middle value.

The halving idea

To find 7 in {1, 3, 5, 7, 9, 11}: look at the middle (5). Since 7 > 5, the answer must be in the right half, so we ignore the left. We repeat on the smaller range until we land on 7. Each step cuts the work in half.

The Java program

public class BinarySearch {
    public static void main(String[] args) {
        int[] a = {1, 3, 5, 7, 9, 11};
        int target = 7;
        int low = 0, high = a.length - 1, pos = -1;

        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (a[mid] == target) { pos = mid; break; }
            else if (a[mid] < target) low = mid + 1;   // go right
            else high = mid - 1;                       // go left
        }
        System.out.println(pos == -1 ? "Not found" : "Found at " + pos);
    }
}
Found at 3

We keep a low and high range and check the middle. If the middle is too small we move low right; too big, we move high left. We stop when found or the range is empty.

Dry run

Dry Run — Binary Search: find 7 in {1,3,5,7,9,11}
Steplowhighmida[mid]Compare with 7What happens
105255 < 7low = 3 (go right)
235499 > 7high = 3 (go left)
333377 == 7Found! pos = 3 (STOP)
💡 Understand it this way

Each step checks the middle and throws away the half that cannot hold 7. The range shrinks fast (6 → 3 → 1), so it finds the answer in just 3 steps.

Why sorted is required

Binary search decides which half to keep by comparing the target with the middle value. That only works if everything left of the middle is smaller and everything right is larger — that is, the array is sorted. On an unsorted array, discarding a half could remove the very item you are looking for, giving wrong results.

Time complexity

  • Binary search: O(log n) — halves the range each step (needs sorted data).
  • Linear search: O(n) — checks each item (works on any array).
  • Space: O(1) — just a few variables.

For a million sorted items, binary search needs about 20 steps versus up to a million for linear search.

Common mistakes

  • Using it on an unsorted array. Sort first, or the result is wrong.
  • Wrong mid formula. Use low + (high - low) / 2 to avoid overflow.
  • Off-by-one on low/high. Move to mid + 1 or mid - 1, not mid.
  • Wrong loop condition. Use low <= high, or you miss the last element.

Summary

  • Binary search finds a value in a sorted array by halving the range.
  • Check the middle, then keep the half that can contain the target.
  • The array must be sorted for it to work.
  • Use mid = low + (high - low) / 2 to avoid overflow.
  • It is O(log n) — far faster than linear search on large sorted data.

Next, sort the data first with bubble sort, or revise Java arrays.

Frequently Asked Questions

What is binary search?
Binary search is a fast way to find an item in a sorted array. It checks the middle element, then discards half the array based on whether the target is smaller or larger, repeating until it finds the item or runs out.
Why must the array be sorted for binary search?
Binary search works by deciding which half to keep based on the middle value. That decision only makes sense if the data is in order. On an unsorted array, discarding a half could throw away the item you want.
What is the time complexity of binary search?
It is O(log n), because each step halves the remaining items. For a million items, it takes only about 20 steps, which is why it is far faster than linear search on large sorted data.
What is the difference between binary search and linear search?
Linear search checks every element one by one (O(n)) and works on any array. Binary search jumps to the middle and halves the range (O(log n)) but needs a sorted array. Binary search is much faster on sorted data.
How do I calculate the middle index?
Use mid = low + (high - low) / 2. This is safer than (low + high) / 2 because it avoids overflow when low and high are very large.
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicReverse String Your progress: 53 / 61 (87%) · Lesson 54 / 61 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free