Skip to content

Instantly share code, notes, and snippets.

@krishnabhargav
Created October 21, 2014 11:52
Show Gist options
  • Save krishnabhargav/4d8949c0138daabc4281 to your computer and use it in GitHub Desktop.
Save krishnabhargav/4d8949c0138daabc4281 to your computer and use it in GitHub Desktop.
isSorted for arrays and seq
def isSorted[A] (items : Seq[A], ordered : (A,A) => Boolean) : Boolean =
(items, items.tail).zipped.forall(ordered)
/*items match {
case null => true
case x :: Nil => true
case x :: y :: xs => ordered (x, y) && isSorted (xs, ordered)
}*/
isSorted(Seq(1,2,3), (a: Int, b: Int) => a < b);
def isArraySorted[A] (items: Array[A], ord : (A,A) => Boolean) : Boolean = {
for(i <- 0 until items.length-1) {
if(ord(items(i), items(i+1))) return true
}
return false
}
isArraySorted(Array(1,2), (a: Int, b :Int) => a < b);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment