Skip to content

Instantly share code, notes, and snippets.

@nikoncode
Created March 22, 2015 19:40
Show Gist options
  • Select an option

  • Save nikoncode/8411e7fbcb386cad8c18 to your computer and use it in GitHub Desktop.

Select an option

Save nikoncode/8411e7fbcb386cad8c18 to your computer and use it in GitHub Desktop.
public static void main(String[] args) {
AbstractPurchase purchases[] = {...};
Arrays.sort(purchases);
print(purchases);
/* http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch(byte[],%20byte)
* binarySearch return index of the search key, if it is contained in the array;
* otherwise, (-(insertion point) - 1). Use it by create comparator without return 0
* (equals) section. binarySearch with this comparator always return insertion point.
*/
final long SEARCH_COST = 90000;
Comparator<AbstractPurchase> comp = new Comparator<AbstractPurchase>() {
@Override
public int compare(AbstractPurchase o1, AbstractPurchase o2) {
if (o1.getCost() > SEARCH_COST) {
return -1;
}
return 1;
}
};
int f = Arrays.binarySearch(purchases, null, comp);
/* Insertion point reverse transformation */
f = -f - 1;
if (f < purchases.length && purchases[f].getCost() == SEARCH_COST) {
int l = f + 1;
while (l < purchases.length && purchases[l].getCost() == SEARCH_COST) {
l++;
}
System.out.printf("[%d,%d)", f, l);
} else {
System.out.println("NOT FOUND");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment