Binary search using recursive technique

import java.io.*;
public class BinarySearchRecursive
{
    static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    static int A[]; int size=0,M=0;
    void input()throws Exception
    {
        System.out.print("Enter the size of the Array to be Searched : ");
        size=Integer.parseInt(br.readLine());
        A=new int[size];
        for(int i=0;i<size;i++)
        {
            int flag=0;
            do
            {
                flag=0;
                System.out.print("Enter the Element No."+(i+1)+" : ");
                A[i]=Integer.parseInt(br.readLine());
                for(int j=0;j<i;j++)
                {
                    if(A[j]==A[i])
                    {
                        flag=1;
                        System.out.println("Duplicate Element Inputted. Try Again");
                    }
                }
            }while(flag==1);
        }
    }
    
    void sort()
    {
        int temp,small,pos;
        for(int i=0;i<A.length;i++)
        {
            small=A[i];
            pos=i;
            for(int j=i+1;j<A.length;j++)
                if(A[j]<small)
                {
                    small=A[j];
                    pos=j;
                }
            temp=A[i];
            A[i]=A[pos];
            A[pos]=temp;
        }
        System.out.println("\nSorted Array is : ");
        for(int j=0;j<A.length;j++)
            System.out.print(A[j]+" ");
    }
    
    void BinSearch(int S,int L,int U)
    {
        if(L<=U)
        {
            M=(int)(U+L)/2;
            if(A[M]<S)
                BinSearch(S,(M+1),U);
            else if(A[M]>S)
                BinSearch(S,L,(M-1));
            else if(A[M]==S)
                System.out.println("Element "+S+" found at Position "+(M+1));
        }
        else
                System.out.println("Element "+S+" not found");
    }
    
    public static void main(String args[])throws Exception
    {
        BinarySearchRecursive obj=new BinarySearchRecursive();
        obj.input();
        obj.sort();
        System.out.print("\nEnter the Element to be Searched : ");
        obj.BinSearch(Integer.parseInt(br.readLine()),0,(A.length-1));
    }
}

No comments:

Post a Comment