Repository navigation
Expand file tree
/
Copy pathMain.java
More file actions
63 lines (52 loc) · 1.47 KB
/
Copy pathMain.java
File metadata and controls
63 lines (52 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main;
public class BinarySearch {
public static void main(String[] args) {
int[] myList = {87, 21, 45, 93};
System.out.println(binarySearch(myList, 93));
System.out.println(binarySearch(myList, 16));
}
public static int binarySearch(int[] list, int item) {
if (isListEmpty(list)) {
return -1;
}
int low = 0;
int high = list.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
int guess = list[mid];
if (guessEqualsItem(guess, item)) {
return mid;
} else if (guessGreaterThanItem(guess, item)) {
high = mid - 1;
} else if(guessLessThanItem(guess, item)) {
low = mid + 1;
}
}
return -1;
}
public static boolean isListEmpty(int[] myList) {
int listSize = myList.length;
if (listSize == 0) {
return true;
}
return false;
}
public static boolean guessEqualsItem(int guess, int item) {
if (guess != item) {
return false;
}
return true;
}
public static boolean guessGreaterThanItem(int guess, int item) {
if (guess < item) {
return false;
}
return true;
}
public static boolean guessLessThanItem(int guess, int item) {
if (guess > item) {
return false;
}
return true;
}
}