# Scala algorithm: Find the minimum item in a rotated sorted array

Published

## Algorithm goal

A rotated sorted array is a sorted array, split into 2 parts, swapped. For example `[1,2,7,9]` can be rotated by changing it to `[7,9,1,2]`. Find the minimum element in this sorted array efficiently.

## Test cases in Scala

``````assert(minItemSortedArray(Array.empty) == None)
assert(minItemSortedArray(Array(1)) == Some(1))
assert(minItemSortedArray(Array(1, 7)) == Some(1))
assert(minItemSortedArray(Array(7, 1)) == Some(1))
assert(minItemSortedArray(Array(9, 1, 7)) == Some(1))
assert(minItemSortedArray(Array(7, 9, 1)) == Some(1))
assert(minItemSortedArray(Array(7, 9, 1, 2)) == Some(1))
assert(minItemSortedArray(Array(7, 9, 1, 2, 4)) == Some(1))
assert(minItemSortedArray(Array(7, 9, 1, 2, 4, 5)) == Some(1))
assert(minItemSortedArray(Array(7, 9, 1, 2, 4, 5, 6)) == Some(1))
assert(minItemSortedArray(Array(6, 7, 8, 9, 1, 2, 4, 5)) == Some(1))
assert(minItemSortedArray(Array(6, 7, 8, 9, 1, 2, 3, 4, 5)) == Some(1))
``````

## Algorithm in Scala

17 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!

## Explanation

The approach to use is very similar to BinarySearch, except for the extra check that there is an extra additional check to find if we have reached the disjunction of the array. (this is © from www.scala-algorithms.com)

## Scala concepts & Hints

1. ### Def Inside Def

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

``````def exampleDef(input: String): String = {
def surroundInputWith(char: Char): String = s"\$char\$input\$char"
surroundInputWith('-')
}

assert(exampleDef("test") == "-test-")
``````

It is also frequently used in combination with Tail Recursion.

2. ### 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!

``````assert(Option(1).flatMap(x => Option(x + 2)) == Option(3))

assert(Option(1).flatMap(x => None) == None)
``````
3. ### Range

The `(1 to n)` syntax produces a "Range" which is a representation of a sequence of numbers.

``````assert((1 to 5).toString == "Range 1 to 5")

assert((1 to 5).reverse.toString() == "Range 5 to 1 by -1")

assert((1 to 5).toList == List(1, 2, 3, 4, 5))
``````
4. ### 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.

``````def sum(from: Int, until: Int): Int =
if (from == until) until else from + sum(from + 1, until)

def thisWillSucceed: Int = sum(1, 5)

def thisWillFail: Int = sum(1, 300)
``````
5. ### Tail Recursion

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

``````def fibonacci(n: Int): Int = {
@scala.annotation.tailrec
def go(i: Int, previous: Int, beforePrevious: Int): Int =
if (i >= n) previous else go(i + 1, previous + beforePrevious, previous)

go(i = 1, previous = 1, beforePrevious = 0)
}

assert(fibonacci(8) == 21)
``````

# Scala Algorithms: The most comprehensive library of algorithms in standard pure-functional Scala

### Study our 89 Scala Algorithms: 6 fully free, 89 published & 0 upcoming

Fully unit-tested, with explanations and relevant concepts; new algorithms published about once a week.

### Explore the 21 most useful Scala concepts

To save you going through various tutorials, we cherry-picked the most useful Scala concepts in a consistent form.

## Register now (free)

Register with GitHub

This gives you access to free test cases & hints for all our 89 published algorithms as well as our installation-free Scala IDE.

You can then choose to subscribe to "Scala Algorithms Unlimited", which gets you access to every current and upcoming algorithm solution. We use Stripe so your data is safe.

We will e-mail you at most once per week with new algorithms and relevant content.
Your data is protected and unsubscribing is straightforward. 