Last active
August 29, 2015 14:17
-
-
Save nikoncode/f03da83c1eea2668a1e6 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) { | |
| 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 = 5300; | |
| AbstractPurchase comp = new AbstractPurchase() { | |
| @Override | |
| public long getCost() { | |
| return SEARCH_COST + 1; | |
| } | |
| }; | |
| int f = Arrays.binarySearch(purchases, comp); | |
| /* Insertion point reverse transformation */ | |
| f = -f - 1; | |
| if (f < purchases.length && purchases[f].getCost() == SEARCH_COST) { | |
| System.out.println("RESULTS:"); | |
| for (int i = f; purchases[i].getCost() == SEARCH_COST; i++) { | |
| System.out.println(purchases[i]); | |
| } | |
| } else { | |
| System.out.println("NOT FOUND"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment