Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

InterpolationSearch and test cases #43

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions src/main/scala/Search/InterpolationSearch.scala
Original file line number Diff line number Diff line change
@@ -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))
}
}
17 changes: 17 additions & 0 deletions src/test/scala/Search/InterpolationSearchSpec.scala
Original file line number Diff line number Diff line change
@@ -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)
}
}