import java.util.*; class BinarySearch { int binarySearch(int arr[], int start, int end, int x) { if(end>=start) { int mid = start+(end-start)/2; if(arr[mid]==x) return mid; else if(arr[mid]>x) return binarySearch(arr, start, mid - 1, x); else if(arr[mid]<x) return binarySearch(arr, mid+1, end, x); } return -1; } public static void main(String[] args) { BinarySearch s = new BinarySearch(); int arr[] = {2, 3, 5, 7, 17, 22, 25, 31}; int n = arr.length; int x = 17; int result = s.binarySearch(arr, 0, n - 1, x); if(result == -1) System.out.println("Element not Found"); else System.out.println("Element Found at index = " + result); } }
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