Skip to content

Instantly share code, notes, and snippets.

@nikoncode
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save nikoncode/849241329a4e04899fdd to your computer and use it in GitHub Desktop.

Select an option

Save nikoncode/849241329a4e04899fdd to your computer and use it in GitHub Desktop.
public static void main(String[] args) {
Commodity commodity = new Commodity("Milk", 10000);
AbstractPurchase purchases[] = {...};
Arrays.sort(purchases);
print(purchases);
/* Search */
int finder = purchases.length;
int result = -1;
/* AbstractPurchase instance with cost returns search value.
* No needed to write own comparator because AbstractPurchase implements 'comparable'.
*/
final int SEARCH_PRICE = 1800000;
AbstractPurchase comp = new AbstractPurchase() {
@Override
public long getCost() {
return SEARCH_PRICE;
}
};
/* Find first occurrence.
* Each iteration find in [0, last_match) part array. */
while ((finder = Arrays.binarySearch(purchases, 0, finder, comp)) >= 0) {
result = finder;
}
if (result >= 0) {
int f = result;
int l = result + 1;
/* In result stored first match. Find last match. */
while (l < purchases.length && purchases[l].compareTo(purchases[f]) == 0) {
l++;
}
/* Print interval */
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