Buffet_Time

dataStructures-binary

Mar 31st, 2016
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. import java.util.Arrays;
  2. public class BinarySearch {
  3. private BinarySearch() { }
  4. public static int indexOf(int[] a, int key) {
  5. int lo = 0;
  6. int hi = a.length - 1;
  7. while (lo <= hi) {
  8. // Key is in a[lo..hi] or not present.
  9. int mid = lo + (hi - lo) / 2;
  10. if (key < a[mid]) hi = mid - 1;
  11. else if (key > a[mid]) lo = mid + 1;
  12. else return mid;
  13. }
  14. return -1;
  15. }
  16. public static int rank(int key, int[] a) {
  17. return indexOf(a, key);
  18. }
  19. public static void main(String[] args) {
  20.  
  21. // read the integers from a file
  22. In in = new In(args[0]);
  23. int[] whitelist = in.readAllInts();
  24. // sort the array
  25. Arrays.sort(whitelist);
  26. // read integer key from standard input; print if not in whitelist
  27. while (!StdIn.isEmpty()) {
  28. int key = StdIn.readInt();
  29. if (BinarySearch.indexOf(whitelist, key) == -1)
  30. StdOut.println(key);
  31. }
  32. }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment