Binary Search In A Simple Way 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 In A Simple Way Example Program

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

    public static void main(String arg[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter number of elements");
        int num = Integer.parseInt(br.readLine());
        int a[] = new int[num];
        System.out.println("Please enter");
        for (int i = 0; i < num; i++) {
            a[i] = Integer.parseInt(br.readLine());
        }
        System.out.println("Enter the element to search");
        int find = Integer.parseInt(br.readLine());
        int index = search(a, find);
        if (index != -1) {
            System.out.println("Element found : " + index);
        } else {
            System.out.println("Element not found");
        }
    }

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

Sample Output

Output is:
Please Enter Values
Enter No Of Elements
5
Please enter
Enter Value #1 : 
67
Enter Value #2 : 
34
Enter Value #3 : 
45
Enter Value #4 : 
90
Enter Value #5 : 
101
Enter the Element to search
45
Element found Position : 3