Skip to content

Instantly share code, notes, and snippets.

@vpetro
Created January 10, 2015 17:04
Show Gist options
  • Save vpetro/a3aebfc05cf9c3a20c46 to your computer and use it in GitHub Desktop.
Save vpetro/a3aebfc05cf9c3a20c46 to your computer and use it in GitHub Desktop.
isSorted
case object P {
def isSorted[A](as: Array[A], ordered:(A,A) => Boolean): Boolean = {
as match {
case _ if as.isEmpty => true
case _ => as.tail.foldLeft((true, as.head)) {
case (t, i) => if (ordered(t._2, i)) (true, i) else (false, i)
}._1
}
}
def isSorted2[A](as: Array[A], ordered:(A,A) => Boolean): Boolean = isSortedSeq(as, ordered)
def isSortedSeq[A](lst: Seq[A], ordered:(A,A) => Boolean): Boolean = {
lst match {
case Seq() => true
case a +: Seq() => true
case a +: as => ordered(a, as.head) && isSortedSeq(as, ordered)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment