Programming Examples

Java recursive function for binary searching


Write a Java Recursive function for Binary Searching

import java.util.*;
class BinarySearch
{
    boolean bin_search(int a[],int l,int h,int n)
    {
        if(l>h)
        {
            return false;
        }
        else
        {
            int mid=(l+h)/2;
            if(n==a[mid])
            {
                return true;
            }
            else
            {
                if(n<a[mid])
                    return(bin_search(a,l,mid-1,n));
                else
                   return(bin_search(a,mid+1,h,n));
            }
        }
    }
    public static void main(String arr[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("How Many Element you want to Enter : ");
        int s=sc.nextInt();
        int num[]=new int[s];
        System.out.println("Enter "+s+" Sorted Element for array : ");
        for(int i=0;i<s;i++)
        {
            num[i]=sc.nextInt();
        }
        System.out.println("Enter Element you want to Search : ");
        int ch=sc.nextInt();
        BinarySearch obj=new BinarySearch();
        boolean ans=obj.bin_search(num,0,s-1,ch);
        if(ans==true)
        {
            System.out.println("Element Found in Array");
        }
        else
        {
           System.out.println("Element Not Found in Array");
        }
    }
}
Output

How Many Element you want to Enter : 

5

Enter 5 Sorted Element for array : 

10

20

30

40

50

Enter Element you want to Search : 

40

Element Found in Array

How Many Element you want to Enter : 

5

Enter 5 Sorted Element for array : 

10

20

30

40

50

Enter Element you want to Search : 

35

Element Not Found in Array

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz