# Binary Search in Scala

**Scala | Binary Search**: Here, we will understand about binary search in Scala. We will learn binary search algorithm and its implementation in Scala programming language.

Submitted by Shivang Yadav, on September 21, 2020

Searching is one of the important concepts in programming that has found applications in advanced concepts. There are a lot of algorithms to search for an element from the array.

Here, we will learn about the **Binary search algorithm in Scala**.

## Binary Search

It is a search algorithm to find an element in the sorted array. The time complexity of binary search is **O(log n). **The working principle of binary search is **divide and conquer. **And the array is required to be **sorted array **for searching the element.

In binary search algorithm, we take the middle element of the array. And search the required element at this position. There are three cases that arise on comparing the middle element of the array with the searchElement.

- Case 1:
*If (middle element == searchElement)*, return the index of the element. - Case 2:
*If (middle element < searchElement)*, we will search the element in the subarray starting with index after middle index value and ending at the last index of the array. - Case 3:
*If (middle element > searchElement)*, we will search the element in the subarray starting with the first index and ending at the index less than middle index.

The sorting algorithm will continue until the element found or the size of the sub-array created becomes 0.

**Example to show how binary search works,**

Array = {1, 4, 9, 10, 16, 22, 26, 29, 32, 36} searchElement = 4 size = 10 Iteration 1: start = 0, end = 9, mid = (start + end)/2 = (0 + 9)/2 = 4. Element at index 4 is 16. Element 16 > 4. Update end to (4-1) = 3. Iteration 2: start = 0, end = 3, mid = (start + end)/2 = (0 + 3)/2 = 1. Element at index 1 is 4. Element at 4 == 4. Element found at index 1.

Binary search can be implemented using recursive approach or iterative approach.

**Recursive Approach**

In the recursive approach, we will create a function that will be called for each subarray.

**Program:**

object BinarySearch{ def BinarySearchRec(arr: Array[Int], Element_to_Search: Int, start: Int, end: Int): Int = { if (start > end) return -1 var mid = start + (end - start) / 2 if (arr(mid) == Element_to_Search) return mid else if (arr(mid) > Element_to_Search) return BinarySearchRec(arr, Element_to_Search, start, (mid-1)) else return BinarySearchRec(arr, Element_to_Search, (mid+1), end) } def main(args: Array[String]){ val searchElement = 4 val sortedArray = Array(1, 4, 9, 10, 16, 22, 26, 29, 32, 36) var elementIndex = BinarySearchRec(sortedArray, searchElement, 0, 6); if(elementIndex == -1) print("Not Found") else print("Element found at index value " + elementIndex) } }

**Output:**

Element found at index value 1

Here, we have created an array *sortedArray* and *searchElement*, the element to be searched. To find the index of the element, we will use the binary search and implementing it using the recursive approach. The function call itself with different subarrays, based on the searchElement's comparison value with the mid element of the current array.

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

**Ad:**
Are you a blogger? Join our Blogging forum.