Introduction
Binary Search is a highly efficient algorithm used for searching a specific element in a sorted array or list. It works by repeatedly dividing the search interval in half, checking whether the target value is less than or greater than the middle element of the array. This makes it much faster compared to linear search algorithms, particularly for large datasets.
Objective
The main objective of this topic is to demonstrate how to implement the Binary Search algorithm in Java. By the end of this tutorial, you will be able to:
- Understand the concept of Binary Search.
- Implement the algorithm in Java programming language.
- Run and test the Binary Search program with different inputs.
Binary Search Code in Java
import java.util.Arrays;
public class BinarySearch {
// Method to perform Binary Search
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
// Check if target is at the middle
if (arr[mid] == target) {
return mid; // Target found, return index
}
// If target is greater, ignore the left half
if (arr[mid] < target) {
left = mid + 1;
}
// If target is smaller, ignore the right half
else {
right = mid - 1;
}
}
return -1; // Target not found
}
public static void main(String[] args) {
int[] numbers = {2, 3, 4, 10, 40};
int target = 10;
// Perform Binary Search
int result = binarySearch(numbers, target);
if (result == -1) {
System.out.println("Element not found in the array.");
} else {
System.out.println("Element found at index " + result);
}
}
}
Explanation of the Program Structure
The program begins by defining a method binarySearch, which takes a sorted array and a target value as input. The method uses a while loop to repeatedly narrow down the search range by comparing the target value with the middle element of the array. If the target is found, the method returns the index of the element; otherwise, it returns -1 to indicate that the target is not in the array.
The main method initializes a sorted array numbers and a target value. It then calls the binarySearch method to find the target in the array. Based on the result, it prints whether the element was found or not.
How to Run the Program
- Copy the code into a text editor and save it as
BinarySearch.java. - Open a terminal or command prompt, navigate to the directory where the file is saved, and compile the Java program by running the following command:
javac BinarySearch.java
- Run the compiled program using the following command:
java BinarySearch
- The program will output the index of the target element if it is found in the array, or a message indicating that the element is not found.

