Advertisement
debetimi

isSorted

Mar 26th, 2014
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.66 KB | None | 0 0
  1.    @tailrec
  2.   final def isSorted[A](as: Array[A], gt: (A, A) => Boolean): Boolean = {
  3.     as match {
  4.       case Array() => true
  5.       case Array(a) => true
  6.       case Array(a, b) => !gt(a, b)
  7.       case _ => if (gt(as(0), as(1))) false else isSorted(as.tail, gt)
  8.     }
  9.   }
  10.  
  11.  
  12.   // Exercise 2: Implement a polymorphic function to check whether
  13.   // an `Array[A]` is sorted
  14.   def isSorted[A](as: Array[A], gt: (A,A) => Boolean): Boolean = {
  15.     @annotation.tailrec
  16.     def go(i: Int, prev: A): Boolean =
  17.       if (i == as.length) true
  18.       else if (gt(as(i), prev)) go(i + 1, as(i))
  19.       else false
  20.     if (as.length == 0) true
  21.     else go(1, as(0))
  22.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement