Binary Search Program - Java

In computer science, a binary search or half-interval search algorithm finds the position of a specified input value (the search "key") within an array sorted by key value. In each step, the algorithm compares the search key value with the key value of the middle element of the array. If the keys match, then a matching element has been found and its index, or position, is returned. Otherwise, if the search key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the search key is greater, on the sub-array to the right. If the remaining array to be searched is empty, then the key cannot be found in the array and a special "not found" indication is returned. [From Wikipedia]

Below is the implement of Binary Search in Java.



import java.util.Scanner;
import java.util.Arrays;

class firstapp
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("\nEnter no. of elements :: ");
        int no = sc.nextInt();
        int arr[] = new int[no];
        int item;
               
        for(int i=0; i<no; i++)
        {
            System.out.print("\nEnter no."+i+" :: ");
            arr[i] = sc.nextInt();           
        }
       
        Arrays.sort(arr);
       
        System.out.print("\nPlease insert element you want to search :: ");
        item = sc.nextInt();
       
        int lb=0, ub=no-1, mid;
       
        if(ub==lb)
        {
            if(arr[lb] == item)
            {
                System.out.print("\nElement is at "+lb+" position.");
            }
            else
            {
                System.out.print("\nElement not found.");
            }
        }
        else
        {       
            mid = (lb+ub)/2;
            while(ub != lb && arr[mid] != item)
            {
                if(arr[mid] < item)
                {
                    lb = mid+1;
                }
                else if(arr[mid] > item)
                {
                    ub = mid-1;
                }
                mid = (lb+ub)/2;
            }
            if(arr[mid] == item)
            {
                System.out.print("\nElement is at "+mid+" position.");
            }
            else
            {
                System.out.print("\nElement not found.");
            }
        }       
    }   
}

Post a Comment