Search element using binary search technique

Q.  Write a program to search user defined element from a list by using binary search.

Answer:

Binary Search:
Binary search works only on sorted array elements. Search the sorted array by dividing the search interval in half. If the value of search key is less than the item in the middle of the interval, then the it shifts to the lower half otherwise into the upper half.

So, let’s see how to find an element using binary search algorithms.

BinarySearch.java

import java.util.Scanner;
class BinarySearch
{
    public static void main(String args[])
    {
        int count, num, search, array[], first, last, middle;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter number of elements:");
        num = input.nextInt();
        array = new int[num];

        System.out.println("Enter " + num + " integers");
        for (count = 0; count < num; count++)
        array[count] = input.nextInt();

        System.out.println("Enter the search value:");
        search = input.nextInt();
        first = 0;
        last = num - 1;
        middle = (first + last)/2;

        while( first <= last )
        {
            if ( array[middle] < search )
                first = middle + 1;
            else if ( array[middle] == search )
            {
                System.out.println(search + " found at location " + (middle + 1) + ".");
                break;
            }
            else
            {
                last = middle - 1;
            }
            middle = (first + last)/2;
        }
        if ( first > last )
            System.out.println("Not found! "+search + " is not present in list.\n");
    }
}


Output:

binary search