Created
January 10, 2015 17:04
-
-
Save vpetro/a3aebfc05cf9c3a20c46 to your computer and use it in GitHub Desktop.
isSorted
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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