Geography, asked by scrawat9876, 5 months ago

write java program to perform binary search on a given one dimensional array .array using recursive function​

Answers

Answered by sarithanaresh789
0

Answer:

hiii

Explanation:

We basically ignore half of the elements just after one comparison.

Compare x with the middle element.

If x matches with middle element, we return the mid index.

Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half.

Else (x is smaller) recur for the left half.

Recursive implementation of Binary Search

We basically ignore half of the elements just after one comparison.

Compare x with the middle element.

If x matches with middle element, we return the mid index.

Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half.

Else (x is smaller) recur for the left half.

Recursive implementation of Binary Search

We basically ignore half of the elements just after one comparison.

Compare x with the middle element.

If x matches with middle element, we return the mid index.

Answered by mpd20700
0

Answer:

import java.util.*;

class Binary_Search

{

   public static void main(String[]args)

   {

       Binary_Search obj=new Binary_Search();

       Scanner sc=new Scanner(System.in);

       int arr[]=new int[10];

       int search, low, high,mid,index;

       low=0;high=arr.length-1;

       System.out.println("Enter 10 numbers in the ascending order");

       for(int i=0;i<10;i++)

       {

           arr[i]=sc.nextInt();

       }

       System.out.println("Enter a number to search");

       search=sc.nextInt();

       index=obj.BinSearch(arr,low,high,search);

       if(index==-1)

       {

           System.out.println("Element not found in the array");

       }

       else

       {

           System.out.println("Element is present in the array at index: "+index);

       }

   }

   public int BinSearch(int arr[],int low,int high,int search)

   {

       int mid;

       if(low>high)

       {

           return(-1);

       }

       else

       {

           mid=(low+high)/2;

           if(search==arr[mid])

           {

               return mid;

           }

           else if(search>arr[mid])

           {

               low=mid+1;

           }

           else  

           {

               high=mid-1;

           }

           return(BinSearch(arr,low,high,search));

       }

   }

}

Similar questions