# Scala algorithm: Binary search a generic Array

Published , last updated

## Algorithm goal

A binary search finds the index of a target item in a *sorted* array. The goal is to implement the algorithm using pure-functional Scala.

Binary search runs in \(O(\log{n})\), which is faster than a linear search (\(O(n)\)).

This algorithm works by iteration: we compare the middle element to the target element; if the middle element is higher than the target, the algorithm checks the left side (ie. run the algorithm against the smaller elements), and likewise for the right side. Once equality is found, we return the result; if the range of checking is exhausted, we return a None to indicate that (in other languages, this would also be -1, or in different implementations of the algorithm, also return the element position closest to the target element, for the purpose of finding where to insert the element).

## Test cases in Scala

```
assert(binarySearch(Array.empty[Int], 2) == None)
assert(binarySearch(Array(1), 2) == None)
assert(binarySearch(Array(1, 2), 2) == Some(1))
assert(binarySearch(Array(1, 3), 2) == None)
assert(binarySearch(Array(1, 2, 3), 2) == Some(1))
assert(binarySearch(Array(1, 3, 3), 2) == None)
assert(binarySearch(Array(1, 1, 2, 3), 2) == Some(2))
assert(binarySearch(Array(1, 3, 4), 2) == None)
assert(binarySearch(Array(1, 3, 4, 5), 6) == None)
assert(binarySearch(Array(1, 2, 3, 4, 5), 2) == Some(1))
```

## Algorithm in Scala

18 lines of Scala (version 2.13), showing how concise Scala can be!

## Explanation

The Scala implementation uses the Range concept in order to achieve a more terse solution, in particular by defining the range for the next iteration in terms of the previous range, rather than dealing with raw indices.

This is a very powerful concept because you notice that in Scala, algorithms can be quite self-explanatory whereas in some C/Python algorithm implementations one would have to refer to documentation and comments for an explanation. Documentability is crucial in sharing knowledge. (this is Â© from www.scala-algorithms.com)

## Scala concepts & Hints

### Def Inside Def

A great aspect of Scala is being able to declare functions inside functions, making it possible to reduce repetition.

It is also frequently used in combination with Tail Recursion.

### Drop, Take, dropRight, takeRight

Scala's `drop` and `take` methods typically remove or select `n` items from a collection.

### Option Type

The 'Option' type is used to describe a computation that either has a result or does not. In Scala, you can 'chain' Option processing, combine with lists and other data structures. For example, you can also turn a pattern-match into a function that return an Option, and vice-versa!

### Ordering

In Scala, the 'Ordering' type is a 'type class' that contains methods to determine an ordering of specific types.

### Range

The

`(1 to n)`

syntax produces a "Range" which is a representation of a sequence of numbers.### Stack Safety

Stack safety is present where a function cannot crash due to overflowing the limit of number of recursive calls.

This function will work for n = 5, but will not work for n = 2000 (crash with java.lang.StackOverflowError) - however there is a way to fix it :-)

In Scala Algorithms, we try to write the algorithms in a stack-safe way, where possible, so that when you use the algorithms, they will not crash on large inputs. However, stack-safe implementations are often more complex, and in some cases, overly complex, for the task at hand.

### Tail Recursion

In Scala, tail recursion enables you to rewrite a mutable structure such as a while-loop, into an immutable algorithm.

### Type Class

Type classes are one of Scala's most important super-powers: they enable you to add new behaviour to existing classes, without modifying those classes. In many languages, to add a behaviour to a class, you would typically extend it with an interface, and then implement methods against this interface.This, however, does not scale: especially when you have older libraries, you would be forced to make them depend on a new interface, and have to re-build everything.

Type classes are used heavily in Apple's SwiftUI as "extensions" to enable powerful abstraction capabilities.

Type classes enable you to do things like this: