public static <T> int binarySearch(List<T> list, long key, LongComparator<T> c) { int size = list.size(); int low = 0; int high = size - 1; while (low <= high) { int mid = (low + high) >>> 1; T midVal = list.get(mid); int cmp = c.compare(midVal, key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. }
/** * Compares two keys in the right way. * * <p>This method uses the {@link #actualComparator} if it is non-<code>null</code>. Otherwise, it * resorts to primitive type comparisons or to {@link Comparable#compareTo(Object) compareTo()}. * * @param k1 the first key. * @param k2 the second key. * @return a number smaller than, equal to or greater than 0, as usual (i.e., when k1 < k2, k1 * = k2 or k1 > k2, respectively). */ @SuppressWarnings("unchecked") final int compare(final long k1, final long k2) { return actualComparator == null ? ((k1) < (k2) ? -1 : ((k1) == (k2) ? 0 : 1)) : actualComparator.compare(k1, k2); }