MCPcopy Create free account
hub / github.com/careercup/ctci / BinarySearch

Class BinarySearch

java/Chapter 11/Introduction/BinarySearch.java:3–67  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1package Introduction;
2
3public class BinarySearch {
4
5 public static int binarySearch(int[] a, int x) {
6 int low = 0;
7 int high = a.length - 1;
8 int mid;
9
10 while (low <= high) {
11 mid = (low + high) / 2;
12 if (a[mid] < x) {
13 low = mid + 1;
14 } else if (a[mid] > x) {
15 high = mid - 1;
16 } else {
17 return mid;
18 }
19 }
20 return -1;
21 }
22
23 public static int binarySearchRecursive(int[] a, int x, int low, int high) {
24 if (low > high) return -1; // Error
25
26 int mid = (low + high) / 2;
27 if (a[mid] < x) {
28 return binarySearchRecursive(a, x, mid + 1, high);
29 } else if (a[mid] > x) {
30 return binarySearchRecursive(a, x, low, mid - 1);
31 } else {
32 return mid;
33 }
34 }
35
36 // Recursive algorithm to return the closest element
37 public static int binarySearchRecursiveClosest(int[] a, int x, int low, int high) {
38 if (low > high) { // high is on the left side now
39 if (high < 0) return low;
40 if (low >= a.length) return high;
41 if (x - a[high] < a[low] - x) {
42 return high;
43 }
44 return low;
45 }
46
47 int mid = (low + high) / 2;
48 if (a[mid] < x) {
49 return binarySearchRecursiveClosest(a, x, mid + 1, high);
50 } else if (a[mid] > x) {
51 return binarySearchRecursiveClosest(a, x, low, mid - 1);
52 } else {
53 return mid;
54 }
55 }
56
57 public static void main(String[] args) {
58 int[] array = {3, 6, 9, 12, 15, 18};
59 for (int i = 0; i < 20; i++) {
60 int loc = binarySearch(array, i);

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected