Binary search with Recursion

Binary Search

public class RecBinarySearch {
 
    public static int recBinarySearch(int[] sortedArray, int start, int end, int key) 
    {
        
        if (start <=end) {
            int mid = (start+end)/2;  
            if (key < sortedArray[mid]) 
            {
                return recBinarySearch(sortedArray, start, mid-1, key);     
            } else if (key > sortedArray[mid]) 
            {
                return recBinarySearch(sortedArray, mid+1, end , key);   
            } 
            else 
            {
                return mid;   
            }
        }
        return -1;  
    }
 
    public static void main() {
         
        int[] arr1 = {2,45,234,567,876,900,976,999};
        int end=arr1.length-1;
        int index = recBinarySearch(arr1,0,end,999);
        if(index!=-1)
        System.out.println("Element Found at "+index+" index");
        else 
        System.out.println("Element not Found ");
        
       }
}
Binary search with Recursion

Watch java videos

LEAVE A REPLY

Please enter your comment!
Please enter your name here