Last active
August 29, 2015 14:01
-
-
Save billdozr/25e0e607ca54216a4731 to your computer and use it in GitHub Desktop.
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
/**Below are 2 implementations of the same function for checking whether a binary tree is sorted. isSortedA was made by myself as an answer to an exercise in FP in Scala. isSortedB was found on github as an answer to the same exercise. I assume isSortedB is better, but can anyone tell me why (other than the fact that I left out @annotation.tailrec).*/ | |
def isSortedA[A](as: Array[A], gt: (A, A) => Boolean): Boolean = { | |
def go(n: Int): Boolean = { | |
if (n <= 0) true | |
else if (!gt(as(n), as(n-1)))false | |
else go(n-1) | |
} | |
go(as.length-1) | |
} | |
def isSortedB[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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment