Binary Search follows the divide-and-conquer strategy. It’s effective when we need to find a key in a Large data set.
How: In a binary search operation the data set is divided into two parts in the first step. Then if the target value is lower then mid value, all the upper values will be ignored. It will ignore the same lower values in case of the opposite. And this procedure will keep going until there is one value. If it’s the target value then function will return its position, otherwise -1 will be returned. By the way, the data set has to be sorted before we can apply this algorithm.
Binary Search algorithm can either be iterative, or recursive. Let’s see how they look in Java.
The recursive approach:
The iterative approach: