BinarySearch { public static int binarySearch(int[] a, int key) { int low = 0; int high = a.length - 1; while (low <= high) { int mid = (low + high) / 2; int midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; } return -(low + 1); }  static int binarySearch(int[] a, int key);  }
@Test public void elementFound() { Assert.assertEquals(2, BinarySearch.binarySearch(a, 5)); assertThat(BinarySearch.binarySearch(a, 20), is(6)); }
@Test public void elementNotFound() { assertThat(BinarySearch.binarySearch(a, 15), is(lessThan(0))); }
@Test public void emptyArray() { assertThat(BinarySearch.binarySearch(new int[]{}, 99), is(lessThan(0))); }
@Test(expected=NullPointerException.class) public void nullArray() { BinarySearch.binarySearch(null, 99); }