Request for binary search using functions
Cleber Muramoto
cleber at nightcoders.com.br
Sun Dec 9 20:48:00 PST 2012
Hello, every once in a while I come across the problem of having to use an
incompatible key to perform a binary search, e.g.:
int binarySearch(SimpleDateFormat[] array,String pattern){
...
String midVal = array[i].toPattern();
...
}
(array is sorted using (l,r)->l.toPattern().compareTo(r.toPattern()) )
Of course I could use the comparator to search if the pattern where to be
wrapped in a SimpleDateFormat, which is exactly what I don't want (costly
object)!
Couldn't we have an implementation like:
public static <T, K extends Comparable<?>> int binarySearch(final T[] a,
final int fromIndex, final int toIndex, final K key, final Function<T, K>
f) {
...
K midVal = f.apply(array[i]);
...
}
(array is sorted using (l,r)->f(l).compareTo(f(r)) )
?
Cheers!
More information about the lambda-dev
mailing list