public class Main { public static void main(String[] args) { int [] arr= {1,2,3,4,5,6,7,8,9,10}; int target = 5; // which element are we looking for int ans = binarySearch(arr,target); System.out.println(ans); } static int binarySearch(int[] arr,int target) { int start = 0; int end = arr.length - 1; while (start <= end){ int mid=start+(end-start)/2; if(target < arr[mid]){ end=mid-1; } else if(target>arr[mid]){ start=mid+1; } else{ return mid;// ans found } } return -1; // item does not exist in the array } }
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