Computer Science, asked by Krtin6455, 1 year ago

Binary search example step by step using java

Answers

Answered by Anonymous
2

Answer:

import java.util.*;

class binary_search

{

   public void main()

   {

       Scanner sc=new Scanner(System.in);

       System.out.println("Enter the number of elements in the array");

       int n=sc.nextInt();

       int a[]=new int[n];

       System.out.println("Enter the array elements");

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

       {

           a[i]=sc.nextInt();

       }

       System.out.println("Enter the element that needs to be searched");

       int ele=sc.nextInt();

       int f=0;

       int l=n-1;

       int mid=(f+l)/2;

       while(f<=l)

       {

           if(a[mid]==ele)

           {

               System.out.println("Search successful");

               System.out.println("Present at="+(mid+1));

               break;

           }

           else if(ele>a[mid])

           {

               f=mid+1;

           }

           else if(ele<a[mid])

           {

               l=mid-1;

           }

           mid=(f+l)/2;

       }

       if(f>l)

       {

           System.out.println("Search unsuccessful");

       }

   }

}

       

Explanation:

Binary search breaks the array into two .

Then it checks for the entered element .

If the element is not present then the required output is printed .

Similar questions