-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
39 lines (31 loc) · 1021 Bytes
/
BinarySearch.java
File metadata and controls
39 lines (31 loc) · 1021 Bytes
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
public class BinarySearch {
public int binarySearchIteratively (int[] sortedArray, int key, int low, int high) {
int index = Integer.MAX_VALUE;
while (low <= high) {
int mid = low + ((high - low) / 2);
if(sortedArray[mid] < key) {
low = mid + 1;
continue;
}
if (sortedArray[mid] > key) {
high = mid - 1;
continue;
}
if (sortedArray[mid] == key) {
index = mid;
break;
}
}
return index;
}
public static void main(String[] args) {
int[] numbers = {1,2,3,4,5,6,7,8,9,11,15};
int numberToFind = 16;
BinarySearch binarySearch = new BinarySearch();
int result = binarySearch.binarySearchIteratively(numbers, numberToFind, 0,numbers.length - 1);
String message = result != Integer.MAX_VALUE
? String.format("The value is at the index %d", result)
: "Value not exist in array";
System.out.println(message);
}
}