-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
41 lines (33 loc) · 1.06 KB
/
Copy pathBinarySearch.java
File metadata and controls
41 lines (33 loc) · 1.06 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
package algorithms.search.binary;
/**
* Searches for a target value in a sorted array using binary search.
* <p>
* Time Complexity: O(log n) in all cases.
* Space Complexity: O(1).
* <p>
* Use when: Searching in sorted arrays repeatedly.
* Avoid when: Array is unsorted (use linear search) or only one search (linear may be simpler).
* Requirement: Array MUST be sorted.
*/
class BinarySearch {
static int binarySearch(int[] arr, int target) {
int low = 0;
int high = arr.length;
while (low < high) {
int mid = (low + high) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
low = mid;
else
high = mid;
}
return -1;
}
public static void main(String[] args) {
int[] sortedArray = new int[]{4, 8, 15, 16, 23, 42};
System.out.println(binarySearch(sortedArray, 3));
System.out.println(binarySearch(sortedArray, 23));
System.out.println(binarySearch(sortedArray, 8));
}
}