Java Program to Search an Item in an Array Using Binary Search

You are currently viewing Java Program to Search an Item in an Array Using Binary Search

Java program to search an item in an array using binary search

// Java program to search an item in an array 
// using binary search

import java.util.Scanner;
public class Main {

  public static int BinarySearch(int arr[], int low, int high, int item) {
    if (high >= low) {
      int mid = low + (high - low) / 2;

      if (arr[mid] == item)
        return mid;

      if (arr[mid] > item)
        return BinarySearch(arr, low, mid - 1, item);

      return BinarySearch(arr, mid + 1, high, item);
    }
    return -1;
  }

  public static void main(String[] args) {
    Scanner SC = new Scanner(System.in);

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

    int item = 0;
    int pos = 0;

    System.out.printf("Enter item to search: ");
    item = SC.nextInt();

    pos = BinarySearch(arr, 0, arr.length, item);

    if (pos == -1)
      System.out.printf("Item not found.");
    else
      System.out.printf("Item found at %d position.", pos);
  }
}

Output

Enter item to search: 30
Item found at index 2.

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply