Last active
August 29, 2015 14:17
-
-
Save nikoncode/849241329a4e04899fdd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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