Last active
December 12, 2015 00:18
-
-
Save ffbit/4682585 to your computer and use it in GitHub Desktop.
Binary search with Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import org.junit.runner.RunWith | |
| import org.scalatest.junit.JUnitRunner | |
| import org.scalatest.FunSuite | |
| import scala.annotation.tailrec | |
| @RunWith(classOf[JUnitRunner]) | |
| class BinarySearchSuite extends FunSuite { | |
| trait TestBinarySearch { | |
| val v = Vector(1, 2, 4) | |
| } | |
| test("find the first existent element")( | |
| new TestBinarySearch { | |
| assert(binarySearch(v, 1) === 0) | |
| }) | |
| test("find the second existent element")( | |
| new TestBinarySearch { | |
| assert(binarySearch(v, 2) === 1) | |
| }) | |
| test("find the third existent element")( | |
| new TestBinarySearch { | |
| assert(binarySearch(v, 4) === 2) | |
| }) | |
| test("find a smaller non-existent element")( | |
| new TestBinarySearch { | |
| assert(binarySearch(v, 0) === -1) | |
| }) | |
| test("find a bigger non-existent element")( | |
| new TestBinarySearch { | |
| assert(binarySearch(v, 5) === -4) | |
| }) | |
| test("find an in-between non-existent element")( | |
| new TestBinarySearch { | |
| assert(binarySearch(v, 3) === -3) | |
| }) | |
| def binarySearch(a: Vector[Int], needle: Int): Int = { | |
| @tailrec | |
| def binarySearch(low: Int, high: Int): Int = { | |
| if (low <= high) { | |
| val middle = low + (high - low) / 2 | |
| if (a(middle) == needle) | |
| middle | |
| else if (a(middle) < needle) | |
| binarySearch(middle + 1, high) | |
| else | |
| binarySearch(low, middle - 1) | |
| } else | |
| -(low + 1) | |
| } | |
| binarySearch(0, a.length - 1) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment