Binary Search Example Java Program


Definition

A straightforward implementation of binary search is recursive. The initial call uses the indices of the entire array to be searched. The procedure then calculates an index midway between the two indices, determines which of the two subarrays to search, and then does a recursive call to search that subarray. Each of the calls is tail recursive, so a compiler need not make a new stack frame for each call. The variables imin and imax are the lowest and highest inclusive indices that are searched.

Binary Search Example Program

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BinarySearchMain {

    public static void main(String arg[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BinarySearch binarySearch = new BinarySearch(10);
        binarySearch.readData();
        System.out.println("Enter the Element to search");
        int find = Integer.parseInt(br.readLine());
        int index = binarySearch.search(find);

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

class BinarySearch {

    private int data[];
    private int size;

    public BinarySearch(int size) {
        this.data = new int[size];
        this.size = size;
    }

    public void readData() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Please Enter Values");
        for (int i = 0; i < size; i++) {
            System.out.println("Enter Value #"+(i+1)+" : ");
            data[i] = Integer.parseInt(br.readLine());
        }
    }

    public int search(int find) {
        int start = 0;
        int end = data.length - 1;
        int mid;
        while (start <= end) {
            mid = (start + end) / 2;
            if (data[mid] == find) {
                return mid;
            } else if (data[mid] < find) {
                start = mid + 1;
            } else if (data[mid] > find) {
                end = mid - 1;
            }
        }
        return -1;
    }
}

Sample Output

Output is:
Please Enter Values
Enter Value #1 : 
34
Enter Value #2 : 
11
Enter Value #3 : 
22
Enter Value #4 : 
45
Enter Value #5 : 
78
Enter the Element to search
45
Element found Position : 4