Java Binary Search Program

Introduction

Binary Search is one of the fastest searching algorithms in Java. It is used to search for an element in a sorted array by repeatedly dividing the search range into half. Instead of checking every element one by one like Linear Search, Binary Search compares the target value with the middle element and eliminates half of the remaining elements in each step.

Because it reduces the search space by half after every comparison, Binary Search has a time complexity of O(log n), making it much faster than Linear Search for large datasets.

For example:

Sorted Array:


10 20 30 40 50 60 70

Search Element:


50

Output

Element found at index 4

Binary Search is widely used in databases, search engines, operating systems, and many software applications where fast searching is required.

In this tutorial, you’ll learn how Binary Search works, its algorithm, Java implementation, iterative and recursive approaches, time complexity, advantages, disadvantages, interview questions, and more.

What is Binary Search?

Binary Search is a searching algorithm that works only on sorted arrays or collections.

Instead of checking every element sequentially, Binary Search repeatedly:

  1. Finds the middle element.
  2. Compares the middle element with the target.
  3. Searches either the left half or the right half.
  4. Repeats until the element is found or the search space becomes empty.

Example:


Array:
10 20 30 40 50 60 70

Search = 50

Middle = 40

50 > 40

Search Right Half
50 60 70
Middle = 60
50 < 60

Search Left Half
50

Element Found

Prerequisites

Before using Binary Search, ensure that:

  • The array is sorted in ascending or descending order.
  • You know whether the data is sorted in ascending or descending order.
  • Binary Search is not suitable for unsorted arrays.

Syntax


int low = 0;
int high = array.length - 1;
while (low <= high) {
    int mid = (low + high) / 2;
    if (array[mid] == key)
        return mid;
    else if (array[mid] < key)
        low = mid + 1;
    else
        high = mid - 1;
}

Java Binary Search Program (Iterative Approach)


public class BinarySearch {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50, 60, 70};
        int key = 50;
        int low = 0;
        int high = numbers.length - 1;
        boolean found = false;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (numbers[mid] == key) {
                System.out.println("Element found at index: " + mid);
                found = true;
                break;
            } else if (numbers[mid] < key) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        if (!found) {
            System.out.println("Element not found.");
        }
    }
}

Output

Element found at index: 4

How Binary Search Works?

Consider the following sorted array:


10 20 30 40 50 60 70

Search Element:
50

Step 1
Middle = 40

Since 50 > 40, search the right half.

Step 2
50 60 70

Middle = 60
Since 50 < 60, search the left half.

Step 3
50

Element found.

Java Binary Search Using Recursion


public class BinarySearch {
    static int binarySearch(int[] arr, int low, int high, int key) {
        if (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] == key)
                return mid;
            if (arr[mid] > key)
                return binarySearch(arr, low, mid - 1, key);
            return binarySearch(arr, mid + 1, high, key);
        }
        return -1;
    }
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50, 60, 70};
        int index = binarySearch(numbers, 0, numbers.length - 1, 60);
        if (index != -1)
            System.out.println("Element found at index: " + index);
        else
            System.out.println("Element not found.");
    }
}

Output

Element found at index: 5

Java Binary Search Using User Input


import java.util.Scanner;
public class BinarySearch {
    public static void main(String[] args) {
        int[] numbers = {5, 10, 15, 20, 25, 30, 35};
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter number to search: ");
        int key = scanner.nextInt();
        int low = 0;
        int high = numbers.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (numbers[mid] == key) {
                System.out.println("Element found at index: " + mid);
                scanner.close();
                return;
            } else if (numbers[mid] < key) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        System.out.println("Element not found.");
        scanner.close();
    }
}

Output

Enter number to search:
25
Element found at index: 4

Algorithm

  1. Read the sorted array.
  2. Initialize low and high.
  3. Find the middle element.
  4. Compare the middle element with the target value.
  5. If equal, return the index.
  6. If the target is greater, search the right half.
  7. If the target is smaller, search the left half.
  8. Repeat until the element is found or the search range becomes empty.

Flowchart


       Start
         │
 Read Sorted Array
         │
Initialize Low and High
         │
Find Middle Element
         │
  Element Found?
  ┌──────┴──────┐
Yes            No
  │             │
Print Index    Search Left or Right Half
  │             │
  └──────┬──────┘
         │
        End

Time Complexity

Case Time Complexity
Best Case O(1)
Average Case O(log n)
Worst Case O(log n)

Binary Search is much faster than Linear Search because the search space is halved after every comparison.

Space Complexity

Approach Space Complexity
Iterative O(1)
Recursive O(log n)

Advantages of Binary Search

  • Very fast searching algorithm.
  • Time complexity is O(log n).
  • Efficient for large sorted datasets.
  • Requires fewer comparisons than Linear Search.
  • Widely used in real-world software systems.

Disadvantages of Binary Search

  • Works only on sorted data.
  • Sorting the data first may require additional time.
  • Recursive implementation uses additional stack memory.
  • Not suitable for linked lists due to the lack of direct index access.

Binary Search vs Linear Search

Feature Binary Search Linear Search
Data Requirement Sorted Array Any Array
Best Case O(1) O(1)
Average Case O(log n) O(n)
Worst Case O(log n) O(n)
Suitable for Large Data Yes No

Common Mistakes

1. Using an Unsorted Array

Incorrect:


int[] arr = {30, 10, 50, 20};

Binary Search produces incorrect results on unsorted arrays.

Correct:


int[] arr = {10, 20, 30, 40, 50};

2. Incorrect Middle Calculation

Incorrect:


int mid = (low + high) / 2;

Better:


int mid = low + (high - low) / 2;

This avoids integer overflow for very large arrays.

3. Incorrect Loop Condition

Incorrect:


while(low < high)

Correct:


while(low <= high)

4. Forgetting to Update Low or High

Always update the search boundaries after each comparison.


low = mid + 1;
high = mid - 1;

5. Forgetting to Handle "Element Not Found"

Always display an appropriate message if the element does not exist in the array.

Real-Life Applications

Binary Search is widely used in:

  • Database indexing
  • Search engines
  • Dictionary applications
  • Phone contact search
  • Library management systems
  • Online shopping filters
  • Operating systems
  • Compiler optimization
  • Gaming leaderboards

Summary

The Java Binary Search program is one of the most important searching algorithms every Java programmer should learn. It demonstrates how the Divide and Conquer technique can significantly improve search performance by reducing the search space by half in each step.

Binary Search provides an O(log n) average and worst-case time complexity, making it far more efficient than Linear Search for large datasets. However, it requires the input array to be sorted before searching.

Related Java Tutorials