☞To use this technique elements of an array must be in ascending or descending order.
☞Procedure :
First find the middle element of the array. Compare the middle element with the desired item. After this step there are three cases: 1) If middle element is the desired item, then search is successful. if(arr[middle])==numSearch) 2) If middle element is less than the desired item, then search the second half of the array. first=middle+1; 3) If middle element is greater than the desired item, then search the first half of the array. last=middle-1;
import java.util.*; class BinarySearch{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); System.out.println("Enter the size"); int size=sc.nextInt(); int arr[]=new int[size]; int i, numSearch, flag=1; System.out.println("Enter the elements"); for(i=0;i<arr.length;i++) arr[i]=sc.nextInt(); System.out.println("Enter the number to be searched"); numSearch=sc.nextInt(); int first=0; int last=size-1; int middle; while(first<=last){ middle=(first+last)/2; if(numSearch==arr[middle]){ flag=0; break; } else if(numSearch>arr[middle]) first=middle+1; else last=middle-1; } if(flag==0) System.out.println("The number is present"); else System.out.println("The number is not present"); } }
Enter the size 5 Enter the elements 10 20 30 40 50 Enter the number to be searched 66 Ther number is not present