Computer Science, asked by susama35, 1 year ago

What are the conditions required for Binary Search?​

Answers

Answered by GENIUS1223
0

So part of the precondition for binary search is: the array must already be sorted. But that's not good enough: it has to be sorted in the right order — for example, if it's sorted in descending numeric order, the binary search will shoot right to the wrong end (unless it happens to get lucky on the first probe).

Answered by Anonymous
8

The conditions required for binary search are as follows :-

1 ) The data must be sorted before the searching .

2 ) The data must be sorted in the correct order ( ascending / descending ) so that it matches with the program logic .

NOTE :-

Binary search is the shortest method and is less time consuming .

The element is search by dividing the data from the middle .

The code in JAVA for binary search is :

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");

       }

   }

}  

Similar questions