Binary Search in Java

Binary search is a search algorithm used to find the position of a target value within a sorted array. It works by repeatedly dividing the search interval in half and comparing the target value with the middle element of the array. If the target value matches the middle element, the search is successful. If the target value is less than the middle element, the search continues in the lower half of the array. If the target value is greater than the middle element, the search continues in the upper half of the array. This process is repeated until the target value is found or the search interval becomes empty. Binary search is efficient for sorted arrays and has a time complexity of O(log n), where n is the number of elements in the array.


Raki Adhikary

1/15/20231 min read

import java.util.*;

public class BinarySearchWithoutMethods {

public static void main(String args[]) {

Scanner scanner = new Scanner(;

// Asking for the size of the array

System.out.println("Enter the size of the array:");

int size = scanner.nextInt();

// Creating an array to store the elements

int array[] = new int[size];

// Asking the user to input the sorted array elements

System.out.println("Enter " + size + " elements in sorted order:");

for (int i = 0; i < size; i++) {

array[i] = scanner.nextInt();


// Asking for the element to search

System.out.println("Enter the element to search:");

int target = scanner.nextInt();

// Initializing variables for binary search

int low = 0;

int high = size - 1;

int mid;

boolean found = false;

// Binary Search Algorithm

while (low <= high) {

mid = (low + high) / 2;

// If the element is found at mid

if (array[mid] == target) {

found = true;

System.out.println("Element " + target + " found at index " + mid);



// If the target is greater, search in the right half

else if (array[mid] < target) {

low = mid + 1;


// If the target is smaller, search in the left half

else {

high = mid - 1;



// If the element is not found

if (!found) {

System.out.println("Element " + target + " not found in the array.");





Your Code is here