Skip to content

Commit 5418241

Browse files
committed
Create BinarySearch in Scala
1 parent 5bc31f4 commit 5418241

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -228,8 +228,8 @@ In order to achieve greater coverage and encourage more people to contribute to
228228
</a>
229229
</td>
230230
<td> <!-- Scala -->
231-
<a href="./CONTRIBUTING.md">
232-
<img align="center" height="25" src="./logos/github.svg" />
231+
<a href="./src/scala/BinarySearch.scala">
232+
<img align="center" height="25" src="./logos/scala.svg" />
233233
</a>
234234
</td>
235235
<td> <!-- Kotlin -->

src/scala/BinarySearch.scala

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import scala.annotation.tailrec
2+
3+
def binarySearch(data: Seq[Int], target: Int): Option[Int] = {
4+
@tailrec
5+
def search(left: Int, right: Int): Option[Int] = {
6+
if (left > right) None
7+
else {
8+
val middle: Int = (left + right) / 2
9+
if (data(middle) == target) Some(middle)
10+
else if (data(middle) < target) search(middle + 1, right)
11+
else search(left, middle - 1)
12+
}
13+
}
14+
search(0, data.size)
15+
}
16+
17+
object Main extends App {
18+
val data: Seq[Int] = Seq(0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12)
19+
val value: Int = 11
20+
println(
21+
s"Value '$value' found in position '${binarySearch(data, value).get}'"
22+
)
23+
}

0 commit comments

Comments
 (0)