└── Binary search in java /Binary search in java: -------------------------------------------------------------------------------- 1 | // Java implementation of iterative Binary Search 2 | class BinarySearch { 3 | // Returns index of x if it is present in arr[l....r], else return -1 4 | int binarySearch(int arr[], int l, int r, int x) 5 | { 6 | while (l <= r) { 7 | int mid = (l + r) / 2; 8 | 9 | // If the element is present at the 10 | // middle itself 11 | if (arr[mid] == x) { 12 | return mid; 13 | 14 | // If element is smaller than mid, then 15 | // it can only be present in left subarray 16 | // so we decrease our r pointer to mid - 1 17 | } else if (arr[mid] > x) { 18 | r = mid - 1; 19 | 20 | // Else the element can only be present 21 | // in right subarray 22 | // so we increase our l pointer to mid + 1 23 | } else { 24 | l = mid + 1; 25 | } 26 | } 27 | 28 | // We reach here when element is not present 29 | // in array 30 | return -1; 31 | } 32 | 33 | // Driver method to test above 34 | public static void main(String args[]) 35 | { 36 | BinarySearch ob = new BinarySearch(); 37 | 38 | int arr[] = { 2, 3, 4, 10, 40 }; 39 | int n = arr.length; 40 | int x = 10; 41 | int result = ob.binarySearch(arr, 0, n - 1, x); 42 | 43 | if (result == -1) 44 | System.out.println("Element not present"); 45 | else 46 | System.out.println("Element found at index " 47 | + result); 48 | } 49 | } 50 | --------------------------------------------------------------------------------