From b6ea63d12f67bb64fbf3e5ea9a87899780714a67 Mon Sep 17 00:00:00 2001 From: Chris Kolonas Date: Sat, 18 Jan 2020 22:06:25 +0200 Subject: [PATCH] InterpolationSearch and test cases --- .../scala/Search/InterpolationSearch.scala | 45 +++++++++++++++++++ .../Search/InterpolationSearchSpec.scala | 17 +++++++ 2 files changed, 62 insertions(+) create mode 100644 src/main/scala/Search/InterpolationSearch.scala create mode 100644 src/test/scala/Search/InterpolationSearchSpec.scala diff --git a/src/main/scala/Search/InterpolationSearch.scala b/src/main/scala/Search/InterpolationSearch.scala new file mode 100644 index 0000000..6e51587 --- /dev/null +++ b/src/main/scala/Search/InterpolationSearch.scala @@ -0,0 +1,45 @@ +package Search + +/* + An implementation of the Interpolation algorithm to search an + element in a sorted list of uniformly distributed values. + Interpolation algorithm is based on the binary search algorithm but instead of going to + the middle element, it checks elements closer to the edges. + */ +object InterpolationSearch { + /** + * + * @param arr a sequence of uniformly distributed values + * @param elem an integer to search for in @arr + * @return index of the @elem else -1 + */ + def interpolationSearch(arr: List[Int], elem: Int): Int = { + var low = 0 + var high = arr.size - 1 + + while (low <= high && elem>=arr(low) && elem <=arr(high)) { + //The interpolation formula that decides the next position keeping the uniform distribution in mind. + var pos = low + ((elem - arr(low)) * (high - low) / (arr(high) - arr(low))) + //Target index found + if (arr(pos) == elem) { + return pos + } + //If target is bigger, search right part of list. + else if (arr(pos) < elem) { + low = pos + 1 + } + //If target is lower, search left part of list. + else { + high = pos - 1 + } + } + //If element is not found. + -1 + } + def main(args:Array[String]):Unit ={ + val arr = List(10, 12, 13, 16, 18, 19, 20, 21, + 22, 23, 24, 33, 35, 42, 47) + + println(interpolationSearch(arr,48)) + } +} diff --git a/src/test/scala/Search/InterpolationSearchSpec.scala b/src/test/scala/Search/InterpolationSearchSpec.scala new file mode 100644 index 0000000..1dfc0e6 --- /dev/null +++ b/src/test/scala/Search/InterpolationSearchSpec.scala @@ -0,0 +1,17 @@ +package Search + +import org.scalatest.FlatSpec + +class InterpolationSearchSpec extends FlatSpec { + "An Interpolation Search" should "return the index of an element in an array" in{ + val l = List.range(1,10) + assert(InterpolationSearch.interpolationSearch(l,2)===1) + assert(InterpolationSearch.interpolationSearch(l,9)===8) + } + + it should "return -1 if the element is not found in the list" in{ + val l = List(10, 12, 13, 16, 18, 19, 20, 21, + 22, 23, 24, 33, 35, 42, 47) + assert(InterpolationSearch.interpolationSearch(l,48) === -1) + } +}