Binary Search is an algorithm that helps us find an element in a sorted array in O(log n) time. Its algorithm works on the principle of Divide and Conquer and it works only when the available data is sorted.
Now, when we are using binary search three situation arise:
- If the middle element is the element to be searched, we return the index of the middle element.
- If the middle element is smaller than the element to be searched, we search in the sub-array to the right (Mid to End) in the same way (Get the new middle and check all the three cases again). We search in the right sub-array because the data is sorted, thus all elements before middle element will also be either less than or equal to the middle element.
- If the middle element is greater than the element to be searched, we search in the sub-array to the left(Start to Mid).
This process is continued until either we find the element to be searched or the size of the sub-array reduces to zero.
Example:
👁 Binary Search in Scala
There are three ways to perform Binary Search in Scala.
Recursive Approach
In recursive approach, we recursively call for the implemented binary search algorithm with updated values of start and end until either we match the middle element with the element to be searched or the array size reduces to zero. Below is the code for the recursive approach of Binary Search in Scala.
Output
Element found at Index 3
Iterative approach
In iterative approach, we run a while loop until we either find the element to be searched or the array size reduces to zero. Below is the code for iterative approach of Binary Search in Scala.
<
Output
Element found at Index 5
Pattern Matching And Functional Programming Approach
In this, we first match the middle element with the element to be searched. If the element is present, we return the index of it. Otherwise, we keep calling the created function with the updated parameters. Below is the code for the approach:
Output
Element not found