Description
Binary search is one of the famous and fundamental algorithm in computer science which solves a large number of problems in developing applications and APIs. It uses divide and conquer approach to find out the element.Here, we will be writing a sample program in java that implements binary search.The given array is a sorted array of n elements and we have to search the position a given element inside the array.
SampleBinarySearch .javapublic class SampleBinarySearch { public int binarySearch(int[] arr, int key) { int start = 0; int end = arr.length - 1; while (start <= end) { int mid = (start + end) / 2; if (key == arr[mid]) { return mid; } if (key < arr[mid]) { end = mid - 1; } else { start = mid + 1; } } return -1; } public static void main(String[] args) { SampleBinarySearch sbs = new SampleBinarySearch(); int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16 }; System.out.println("Key 14's position: " + sbs.binarySearch(arr, 14)); int[] arr1 = { 6, 34, 78, 123, 430, 900 }; System.out.println("Key 430's position: " + sbs.binarySearch(arr1, 430)); } }
Worst case performance: O(log n)
Best case performance: O(1)