@Test public void testFirstOccurance() { final int[] arr = { -1, -10, 2, 108, 108, 243, 285, 285, 285, 401 }; Assert.assertEquals(-1, firstOccurrence(arr, 500)); Assert.assertEquals(3, firstOccurrence(arr, 101)); }
public static int firstOccurrence(final int[] arr, final int key) { int index = -1; int left = 0; int right = arr.length - 1; if (right < 0 || arr[right] <= key) { return index; } int mid = left + ((right - left) >>> 1); for (; left <= right; mid = left + ((right - left) >>> 1)) { if (arr[mid] > key) { index = mid; right = mid - 1; } else { left = mid + 1; } } return index; }
PracticeQuestionsCh11 { public static int firstOccurrence(final int[] arr, final int key) { int index = -1; int left = 0; int right = arr.length - 1; if (right < 0 || arr[right] <= key) { return index; } int mid = left + ((right - left) >>> 1); for (; left <= right; mid = left + ((right - left) >>> 1)) { if (arr[mid] > key) { index = mid; right = mid - 1; } else { left = mid + 1; } } return index; } }
PracticeQuestionsCh11 { public static int firstOccurrence(final int[] arr, final int key) { int index = -1; int left = 0; int right = arr.length - 1; if (right < 0 || arr[right] <= key) { return index; } int mid = left + ((right - left) >>> 1); for (; left <= right; mid = left + ((right - left) >>> 1)) { if (arr[mid] > key) { index = mid; right = mid - 1; } else { left = mid + 1; } } return index; }  }
PracticeQuestionsCh11 { public static int firstOccurrence(final int[] arr, final int key) { int index = -1; int left = 0; int right = arr.length - 1; if (right < 0 || arr[right] <= key) { return index; } int mid = left + ((right - left) >>> 1); for (; left <= right; mid = left + ((right - left) >>> 1)) { if (arr[mid] > key) { index = mid; right = mid - 1; } else { left = mid + 1; } } return index; }  static int firstOccurrence(final int[] arr, final int key); }
PracticeQuestionsCh11 { public static int firstOccurrence(final int[] arr, final int key) { int index = -1; int left = 0; int right = arr.length - 1; if (right < 0 || arr[right] <= key) { return index; } int mid = left + ((right - left) >>> 1); for (; left <= right; mid = left + ((right - left) >>> 1)) { if (arr[mid] > key) { index = mid; right = mid - 1; } else { left = mid + 1; } } return index; }  static int firstOccurrence(final int[] arr, final int key); static final Logger LOGGER; }