Skip to content

Commit

Permalink
Create BinarySearch in Scala
Browse files Browse the repository at this point in the history
  • Loading branch information
kelvins committed Oct 21, 2024
1 parent 5bc31f4 commit 5418241
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,8 @@ In order to achieve greater coverage and encourage more people to contribute to
</a>
</td>
<td> <!-- Scala -->
<a href="./CONTRIBUTING.md">
<img align="center" height="25" src="./logos/github.svg" />
<a href="./src/scala/BinarySearch.scala">
<img align="center" height="25" src="./logos/scala.svg" />
</a>
</td>
<td> <!-- Kotlin -->
Expand Down
23 changes: 23 additions & 0 deletions src/scala/BinarySearch.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import scala.annotation.tailrec

def binarySearch(data: Seq[Int], target: Int): Option[Int] = {
@tailrec
def search(left: Int, right: Int): Option[Int] = {
if (left > right) None
else {
val middle: Int = (left + right) / 2
if (data(middle) == target) Some(middle)
else if (data(middle) < target) search(middle + 1, right)
else search(left, middle - 1)
}
}
search(0, data.size)
}

object Main extends App {
val data: Seq[Int] = Seq(0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12)
val value: Int = 11
println(
s"Value '$value' found in position '${binarySearch(data, value).get}'"
)
}

0 comments on commit 5418241

Please sign in to comment.