Binary Search in Java with Examples

Binary Search is an efficient algorithm for finding an element in a sorted array or collection. It works by repeatedly dividing the search interval in half and comparing the target value (key) with the middle element.

This article shows you how the Binary search algorithm works, and gives two examples (basic, and advanced) to demonstrate the efficiency of Binary Search.

How Binary Search Works?

  1. Start with two pointers: low (beginning of the array) and high (end of the array).
  2. Find the middle element using: mid=low+(high−low)/2
  3. Compare the key with the middle element:
    • If the key matches the middle element, return its index.
    • If the key is smaller, search the left half (high = mid - 1).
    • If the key is larger, search the right half (low = mid + 1).
  4. Repeat until low exceeds high or the key is found.
  5. If the key is not found, return -1.

1. Binary Search Program in Java (Basic example)

This program example demonstrates Binary Search on a sorted array of integers.

package com.javacodepoint.search;

public class BasicBinarySearch {
	
	public static int binarySearch(int[] array, int key) {
		int low = 0;
		int high = array.length - 1;

		while (low <= high) {
			int mid = low + (high - low) / 2; // Calculate mid to prevent overflow
			if (array[mid] == key) {
				return mid; // Key found, return index
			} else if (array[mid] < key) {
				low = mid + 1; // Search in the right half
			} else {
				high = mid - 1; // Search in the left half
			}
		}
		return -1; // Key not found
	}

	public static void main(String[] args) {
		int[] numbers = { 10, 20, 30, 40, 50 };
		int key = 30;

		int result = binarySearch(numbers, key);

		if (result != -1) {
			System.out.println("Element found at index: " + result);
		} else {
			System.out.println("Element not found.");
		}
	}
}

2. Binary Search in Java Program (Advanced example)

This program example demonstrates Binary Search on a sorted list of custom objects. The search is performed based on a specific property (e.g., id).

package com.javacodepoint.search;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Employee {
	private int id;
	private String name;

	public Employee(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	@Override
	public String toString() {
		return "Employee{id=" + id + ", name='" + name + "'}";
	}
}

public class AdvancedBinarySearch {
	
	public static int binarySearch(List<Employee> employees, int key) {
		int low = 0;
		int high = employees.size() - 1;

		while (low <= high) {
			int mid = low + (high - low) / 2;
			Employee midEmployee = employees.get(mid);

			if (midEmployee.getId() == key) {
				return mid; // Key found
			} else if (midEmployee.getId() < key) {
				low = mid + 1; // Search in the right half
			} else {
				high = mid - 1; // Search in the left half
			}
		}
		return -1; // Key not found
	}

	public static void main(String[] args) {
		List<Employee> employees = new ArrayList<>();
		employees.add(new Employee(101, "Alice"));
		employees.add(new Employee(102, "Bob"));
		employees.add(new Employee(103, "Charlie"));

		// Sort the list by ID (Binary Search requires a sorted collection)
		Collections.sort(employees, Comparator.comparingInt(Employee::getId));

		int key = 102;

		int result = binarySearch(employees, key);

		if (result != -1) {
			System.out.println("Employee found: " + employees.get(result));
		} else {
			System.out.println("Employee not found.");
		}
	}
}

Key Differences Between the above Two Examples

AspectBasic ExampleAdvanced Example
Data Type1D array of integersList of custom objects (Employee)
Search TargetIntegerInteger (id property)
ResultIndex of the keyObject matching the search criteria
FlexibilityLimited to primitive typesWorks with any data structure

Key Points to Remember

  1. Binary Search Requirements:
    • The dataset must be sorted.
    • You may need to sort a collection before performing a Binary Search.
  2. Time Complexity:
    • O(log⁡n), where n is the size of the dataset.
    • Much faster than Linear Search for large datasets.

Read also: Linear SearchInterpolation SearchFibonacci SearchExponential SearchTernary Search, and Jump Search.

Java logical programs list


Java Basic Programs

Java String Programs

Java Miscellaneous Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *