Binary search: Difference between revisions

Line 3,174:
 
=={{header|Scala}}==
'''Recursive'''
<lang scala>def binarySearch[A <% Ordered[A]](a: IndexedSeq[A], v: A) = {
def recurse(low: Int, high: Int): Option[Int] = (low + high) / 2 match {
Line 3,183 ⟶ 3,184:
recurse(0, a.size - 1)
}</lang>
Test:
<lang scala>def testBinarySearch(n: Int) = {
val odds = 1 to n by 2
val result = (0 to n).flatMap(binarySearch(odds, _))
assert(result == (0 until odds.size))
println(s"$odds are odd natural numbers")
for (it <- result)
println(s"$it is ordinal of ${odds(it)}")
}
 
def main() = testBinarySearch(12)</lang>
Output:
<pre>Range(1, 3, 5, 7, 9, 11) are odd natural numbers
0 is ordinal of 1
1 is ordinal of 3
2 is ordinal of 5
3 is ordinal of 7
4 is ordinal of 9
5 is ordinal of 11</pre>
 
=={{header|Scheme}}==
Anonymous user