Binary Search

Binary Search


Write a program to search a given element in an array using Binary Search technique. Assume that the array is sorted in ascending order.

import java.util.*;

class BinarySearch
{
    public static void main(String args[])throws InputMismatchException
    {

        Scanner scan=new Scanner(System.in);

        int i, n,l,u,m,ele;
        boolean flag;

        System.out.println("Enter the number of elements : ");
        n = scan.nextInt();

        int a[] = new int[n]; //declare array 

        System.out.println("Enter " + n + " elements for the array.");

        for(i = 0; i < n; i++) 
            a[i] = scan.nextInt();

        System.out.println("Enter the element to be searched : ");
        ele = scan.nextInt();

        flag = false; 

        l=0;//lower limit

        u = n-1;//upper limit

        m = 0;

        while(l <= u){

            m = (l+u)/2;

            if(ele > a[m])
               l = m+1;

            else if(ele < a[m])
               u = m-1;

            else{
                flag = true;
                break;
            }

        }//end of loop

        if(flag){

            System.out.println("Element is present at position " + (m+1));

        }else{

            System.out.println("Element not found.");   

        }

   }//end of main
}//end of class 

Have something to say? Log in to comment on this post.

0 comments