Skip to content

Instantly share code, notes, and snippets.

@shigemk2
Created April 14, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shigemk2/4d94c5bd74a1386285c9 to your computer and use it in GitHub Desktop.
Save shigemk2/4d94c5bd74a1386285c9 to your computer and use it in GitHub Desktop.
def isSorted[A](as: Array[A], gt: (A,A) => Boolean): Boolean = {
@annotation.tailrec
def go(n: Int): Boolean =
if (n >= as.length-1) true
else if (gt(as(n), as(n+1))) false
else go(n+1)
go(0)
}
println(isSorted(Array(1,2,3), ((x: Int, y: Int) => x > y): ((Int, Int) => Boolean)))
println(isSorted(Array(1), ((x: Int, y: Int) => x > y): ((Int, Int) => Boolean)))
def isSorted[A](as: Array[A], gt: (A,A) => Boolean): Boolean = {
as match {
case as if as.length <= 1 => true
case as if gt(as(0), as(1)) == false => isSorted(as.tail, gt)
case _ => false
}
}
println(isSorted(Array(1,2,3), ((x: Int, y: Int) => x > y): ((Int, Int) => Boolean)))
println(isSorted(Array(1), ((x: Int, y: Int) => x > y): ((Int, Int) => Boolean)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment