Class Binary contains an array of an integers (n<=100) that are already arranged in ascending order the subscript of the array elements vary from 0 to n-1 the data members and members function are as follows
Class Name    Binary
Data members 
a[] int array of 100 elements
n Size of the Array
l Location of lower bound
u Locations of upper bound

Member Functions

Binary(int num)  Constructed to initialise n =  num And other instance variables
void readdata() - To fill array elements in ascending order
int binary_search(int v) -   Returns the location of the value v after searching the list by 
using binary search technique using recursion, the function returns -1 if the number is not present in the list.
            
Also write main function




import java.util.*;
class Binary
{
    int a[]=new int[100];
    int l,u,n;
    Binary(int num)
    {
        n=num;
        a=new int[n];
        l=0;
        u = n-1;
    }
    void readdata()
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("enter elements in ascending order");
        for(int i=0;i< n;i++)
        {
            a[i]=sc.nextInt();
        }
    }
    int binary_search(int v)
    {
        if(l>u)
        {
            return -1;
        }
        else
        {
            int m=(l+u)/2;
            if(v==a[m])
                return m;
            else if(v< a[m])
            {
            u=m-1;
            }
            else
            {
            l=m+1;
            }
            return binary_search(v);
        }
    }
    public static void main()
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the element to be searched and size of array respectively");
        int z=sc.nextInt();
        int j=sc.nextInt();
        Binary ob=new Binary(j);
        ob.readdata();
        int r=ob.binary_search(z);
        if(r==-1)
            System.out.println("Value is not present ");
        
        else
            System.out.println("Value is present at index= "+r);
    }
}



     
                     

Contact Us

REACH US

SERVICES

  • CODING
  • ON-LINE PREPARATION
  • JAVA & PYTHON

ADDRESS

B-54, Krishna Bhawan, Parag Narain Road, Near Butler Palace Colony Lucknow
Contact:+ 919839520987
Email:info@alexsir.com