Binary Search - Recursive Implementation
This chapter details the reasoning behind binary search's time complexity
Binary search is a well-known search algorithm that works on an already-sorted input. The basic idea is to successively eliminate half of the remaining search space at each step till either the target is found or there's no more search space left.
Binary search is recursive in nature but can also be implemented iteratively. Below is the recursive implementation of binary search.
Binary Search Implementation
Press + to interact
class Demonstration {public static void main( String args[] ) {int[] input = new int[] { 1, 3, 4, 6, 7, 101, 1009 };System.out.println(binarySearch(0, input.length - 1, 1009, input));System.out.println(binarySearch(0, input.length - 1, -1009, input));System.out.println(binarySearch(0, input.length - 1, 5, input));System.out.println(binarySearch(0, input.length - 1, 6, input));}/*** start and end are inclusive indices** @param start* @param end* @param target* @param input* @return*/public static boolean binarySearch(int start, int end, int target, int[] input) {if (start > end) {return false;}int mid = (start + end) / 2;if (input[mid] == target) {return true;} else if (input[mid] > target) {return binarySearch(start, mid - 1, target, input);} else {return binarySearch(mid + 1, end, target, input);}}}
Recurrence Equation
The recurrence equation for binary search is given below:
...
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.