Binary Search Implementation In Java

Binary Search Implementation In Java

import java.io.*;
 
 
class BinarySearchImpl
{
    public static int Search(int S[], int key, int low,int high)
    {
        if(low>high)
            return -1;
        else
        {
            int mid = (low+high)/2;
            if(key==S[mid])
                return mid+1;  //as array starts from 0 and not 1
            else if (key<S[mid])
                return Search(S,key,low,mid-1);
            else
                return Search(S,key,mid+1,high);
        }
    }
}
 
public class BinarySearch {
    public static void main(String args[])
    {
        DataInputStream in = new DataInputStream(System.in);
        System.out.println(“Enter the sorted array”);
        int n=10,key=0;
        int data[]=new int[n];
        try
        {
        for(int i=0;i<10;i++)
            data[i]=Integer.parseInt(in.readLine());
        }
        catch(Exception e) {}
 
        System.out.println(“Enter the element to be searched”);
        try
        {
            key=Integer.parseInt(in.readLine());
        }
        catch(Exception e) {}
 
        int loc = BinarySearchImpl.Search(data, key, 0, n-1);
 
        if(loc==-1)
            System.out.println(“the element could not be found”);
        else
            System.out.println(“the element is at position”+loc);
 
    }
}
 
 
 
————————–Output———————————————————–
——————————————————————————————-
Enter the sorted array
4
8
9
12
14
17
21
22
56
100
Enter the element to be searched
17
the element is at position6