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