Binary search in Java is a divide and conquer technique used to search an element in an array. The array is assumed to be sorted in ascending order. Below I have shared the program for binary search in Java. You can ask your doubts if you find difficulty to understand the program.
Java Program for Binary Search
import java.util.Scanner; class BinarySearch { public static void main(String ar[]) { int i,mid,first,last,x,n,flag=0; Scanner sc=new Scanner(System.in); System.out.println("nEnter number of elements:"); n=sc.nextInt(); int a[]=new int[n]; System.out.println("nEnter elements of array:"); for(i=0;i<n;++i) a[i]=sc.nextInt(); System.out.println("nEnter element to search:"); x=sc.nextInt(); first=0; last=n-1; while(first<=last) { mid=(first+last)/2; if(a[mid]>x) last=mid-1; else if(a[mid]<x) first=mid+1; else { flag=1; System.out.println("nelement found"); break; } } if(flag==0) System.out.println("nelement not found"); } }
Thank you so much for this simple code ! Really easy to understand and grasp. The other codes like Union of Arrays and Intersection of arrays were brilliant as well ! Really helpful.