Skip to content

Instantly share code, notes, and snippets.

@dacr
Created May 9, 2013 20:07
Show Gist options
  • Save dacr/5550179 to your computer and use it in GitHub Desktop.
Save dacr/5550179 to your computer and use it in GitHub Desktop.
A small algorithm to find the indexof the first element superior or equal to the given value (in an ordered sequence)
#!/bin/sh
exec scala "$0" "$@"
!#
import scala.annotation.tailrec
// ---------------------------------------------------
def searchFirstGreaterOrEqual[T<%Ordered[T]](seq: Seq[T], value: T):Option[Int] = {
@tailrec
def binarysearch(left:Int, right:Int):Option[Int] = {
if (seq(left)>=value) Some(left)
if (seq(right)<value) None // Not found
else {
(left+right)/2 match {
case m if seq(m)==value => Some(m)
case m if seq(m)>value =>
if (m!=left) binarysearch(left, m) else Some(m)
case m if seq(m)<value =>
if (m<right) binarysearch(m+1, right)
else None // Not found
}
}
}
binarysearch(0, seq.size-1)
}
// ---------------------------------------------------
val l1=List(10,20,30,50,100)
def testWith[T<%Ordered[T]](seq:Seq[T], value:T) {
val result = searchFirstGreaterOrEqual(seq, value)
println(s"${value}->${result}")
}
println(s"""Results with ${l1.mkString(" ")}""")
testWith(l1, 0)
testWith(l1, 15)
testWith(l1, 20)
testWith(l1, 55)
testWith(l1, 150)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment