Skip to content

Instantly share code, notes, and snippets.

@ehsanullahjan
Last active July 27, 2016 20:53
Show Gist options
  • Save ehsanullahjan/5b3a76dfe54dc089b5c4 to your computer and use it in GitHub Desktop.
Save ehsanullahjan/5b3a76dfe54dc089b5c4 to your computer and use it in GitHub Desktop.
Tail recursive implementation of Binary Search in Java
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;
}
@ehsanullahjan
Copy link
Author

Of course Java doesn't support tail recursion but if it did, the provided code would be 100% tail recursive.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment