Binary search compares the target value to the middle element of the array.
If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half,
again taking the middle element to compare to the target value, and repeating this until the target value is found.
If the search ends with the remaining half being empty, the target is not in the array.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | public class BinarySearch{ public static void main(String []args){ int[] arr = {1, 2, 4, 5, 7, 11, 12, 15}; int target = 7; System.out.println(binarySearchRec(arr, target, 0, arr.length-1)); System.out.println(binarySearchIter(arr, target)); } // Using recursion public static boolean binarySearchRec(int[] arr,int target,int left,int right){ if(left>right) return false; int mid = left + ((right-left)/2); if(arr[mid]==target) return true; else if(arr[mid]>target) return binarySearchRec(arr, target, left, mid-1); else return binarySearchRec(arr, target, mid+1, right); } // Using Iterative Approach public static boolean binarySearchIter(int[] arr,int target){ int left = 0; int right = arr.length-1; while(left<=right){ int mid = left + ((right-left)/2); if(arr[mid]==target) return true; else if(arr[mid]>target) right = mid - 1; else left = mid + 1; } return false; } } |