Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Comparator;
  3.  
  4. public class RangeBinarySearch {
  5. // Returns the index of the first key in a[] that equals the search key, or -1 if no such key.
  6. // Complexity: O(log N), where N is the length of the array
  7.  
  8. private final static int NOT_FOUND = -1;
  9.  
  10. public static <Key> int firstIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
  11.  
  12. if (a == null || key == null || comparator == null)
  13. throw new java.lang.NullPointerException("No arguments can be empty.");
  14.  
  15. int left = 0;
  16. int right = a.length - 1;
  17.  
  18. while (left < right) {
  19.  
  20. int mid = left + ((right - left) / 2);
  21.  
  22. if (right == mid)
  23. mid--;
  24.  
  25. int c = comparator.compare(a[mid], key);
  26.  
  27. if (c > 0)
  28. right = mid - 1;
  29. else if (c < 0)
  30. left = mid + 1;
  31. else {
  32. right = mid;
  33. if (right == left)
  34. break;
  35. }
  36. }
  37.  
  38. if (left == right && comparator.compare(a[left], key) == 0) {
  39. //System.out.println("First index: " + left);
  40. return left;
  41. }
  42.  
  43. return NOT_FOUND; // NOT_FOUND = -1
  44. }
  45.  
  46.  
  47.  
  48. // Returns the index of the last key in a[] that equals the search key, or -1 if no such key.
  49. // Complexity: O(log N)
  50.  
  51. public static <Key> int lastIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
  52.  
  53. if (a == null || key == null || comparator == null)
  54. throw new java.lang.NullPointerException("No arguments can be empty.");
  55.  
  56. int left = 0;
  57. int right = a.length - 1;
  58.  
  59. while (left < right) {
  60.  
  61. int mid = (left+right)/2;
  62.  
  63. if (left == mid)
  64. mid++;
  65.  
  66. int c = comparator.compare(a[mid], key);
  67.  
  68. if (c > 0)
  69. right = mid - 1;
  70. else if (c < 0)
  71. left = mid + 1;
  72. else {
  73. left = mid;
  74. if (left == right)
  75. break;
  76. }
  77. }
  78.  
  79. if (left == right && comparator.compare(a[right], key) == 0) {
  80. //System.out.println("Last index: " + right);
  81. return right;
  82. }
  83.  
  84. return NOT_FOUND; // NOT_FOUND = -1
  85.  
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement