Binary search problem in two out of 4 test cases

import java.util.*;
public class Main {
public static void main(String args[]) {
int n,item;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
int[] ar=new int[n];
for(int i=0;i<n;i++){
ar[i]=sc.nextInt();
}
item=sc.nextInt();
System.out.print(binarySearch(ar,item));

}
public static int binarySearch(int[] arr,int item){
int lo=0,mid;
int high=arr.length-1;

 while(lo<=high){
	 mid=(lo+high)/2;
	 if(arr[mid]<item){
		 lo=mid+1;}
		 else if(arr[mid]>item){
			 high=mid-1;
            }
         else{
		  return mid;}
		  lo++;
high--; }

return -1;

}
}

Use mid= lo + (high-lo)/2 to avoid integer overflow. And you don’t need to do lo++ and high–.
Rest of the code is correct.

1 Like