Write a program to search an element from the array using binary search technique.

import java.io.*;
public class binary
{
    int a[];
    int u,l,n,m;
    binary(int nn)
    {
        n=nn;
        a=new int[n];
        for(int i=0;i<n;i++)
        {
            a[i]=0;
        }
        l=0;
        u=n-1;
    }
    void readdata()throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        
        System.out.println("enter the elements");
        for(int i=0;i<n;i++)
        {
            a[i]=Integer.parseInt(br.readLine());
        }
        
    }
    int binary_search(int v)
    {
         m=-1;
        while(u<=n-1)
        {
            m=(l+u)/2;
            if(a[m]>v)
            {
                u=m-1;
                m=binary_search(v);
            }
            else if(a[m]<v)
            {
                l=m+1;
                m=binary_search(v);
            }
            else
            break;
        }
        return m;
    }
    void display()
    {
        if(m==-1)
        System.out.println("the element is absent");
        else
        System.out.println("the element is on "+m+" index");
    }
        
    public static void main()throws IOException
    {
        binary obj=new binary(6);
        obj.readdata();
        obj.binary_search(4);
        obj.display();
    }
}       

LEAVE A REPLY

Please enter your comment!
Please enter your name here