Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @tailrec
- final def isSorted[A](as: Array[A], gt: (A, A) => Boolean): Boolean = {
- as match {
- case Array() => true
- case Array(a) => true
- case Array(a, b) => !gt(a, b)
- case _ => if (gt(as(0), as(1))) false else isSorted(as.tail, gt)
- }
- }
- // Exercise 2: Implement a polymorphic function to check whether
- // an `Array[A]` is sorted
- def isSorted[A](as: Array[A], gt: (A,A) => Boolean): Boolean = {
- @annotation.tailrec
- def go(i: Int, prev: A): Boolean =
- if (i == as.length) true
- else if (gt(as(i), prev)) go(i + 1, as(i))
- else false
- if (as.length == 0) true
- else go(1, as(0))
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement