//binary search public class _6 { public static void main(String[] args) { int arr[]={2,4,5,6,7,12,56}; int target=599; int low=0; int high=arr.length-1; int result=bs(arr,low,high,target); if(result==-1){ System.out.println(target+" is not inside this array!!"); } else{ System.out.print(target+" found at index "+result); } } static int bs(int arr[], int low, int high, int target){ if(low<=high){ int mid=(low+high)/2; if(arr[mid]==target){ return mid; } else if(target<arr[mid]){ return bs(arr,low,mid-1,target); } else{ return bs(arr,mid+1,high,target); } } return -1; } }
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