Binary Search in Array

This program performs binary search to find an element in a sorted array.

Problem Statement

Write a Java program to search for a given element in a sorted integer array using binary search.

Source Code

1 public class BinarySearch {
2 public static void main(String[] args) {
3 int[] arr = {5, 10, 15, 20, 25, 30};
4 int key = 20;
5 int low = 0, high = arr.length-1;
6 boolean found = false;
7 while(low <= high) {
8 int mid = (low + high)/2;
9 if(arr[mid] == key) {
10 System.out.println("Element found at index: " + mid);
11 found = true;
12 break;
13 } else if(arr[mid] < key) low = mid+1;
14 else high = mid-1;
15 }
16 if(!found) System.out.println("Element not found");
17 }
18 }

Program Output

Element found at index: 3

Explanation

The array must be sorted, and variables low, high, and mid control the search boundaries: if arr[mid] equals key it's found, if smaller the search continues right, if larger it continues left, demonstrating the binary search algorithm.

Quick Links to Explore