Last active
July 27, 2016 20:53
-
-
Save ehsanullahjan/5b3a76dfe54dc089b5c4 to your computer and use it in GitHub Desktop.
Tail recursive implementation of Binary Search in Java
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
public static <T extends Comparable<? super T>> int rank(T[] seq, T key) { | |
return rank(seq, key, 0, seq.length - 1); | |
} | |
public static <T extends Comparable<? super T>> int rank(T[] seq, T key, int lo, int hi) { | |
if (lo > hi) | |
return -1; | |
int mid = lo + (hi - lo) / 2; | |
int rel = key.compareTo(seq[mid]); | |
if (rel > 0) | |
return rank(seq, key, mid + 1, hi); | |
else if (rel < 0) | |
return rank(seq, key, lo, mid - 1); | |
else | |
return mid; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Of course Java doesn't support tail recursion but if it did, the provided code would be 100% tail recursive.