public class Problem1 { //Celing of a number: public static void main(String[] args) { int[] arr={2,3,5,9,14,16,18}; int ans=binarySearch(arr,15 ); System.out.println(ans); } //return The index //return -1 it doesnot exist static int binarySearch(int[] arr,int target){ int start=0; int end=arr.length-1; while(start<=end){ // int mid=(start+end)/2; might be possible that start + end exceeds the range of int int mid=start+(end-start)/2; if(arr[mid]>target){ end=mid-1; } if(arr[mid]<target){ start=mid+1; } if(arr[mid]==target){ //ans found return mid; } } return end; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter