forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPerfectBinarySearch.java
More file actions
36 lines (29 loc) · 824 Bytes
/
PerfectBinarySearch.java
File metadata and controls
36 lines (29 loc) · 824 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
package Searches;
import java.util.*;
class PerfectBinarySearch{
static int binarySearch(int[] arr, int target)
{
int low = 0 ;
int high = arr.length - 1 ;
while(low <= high) {
int mid =(low + high) / 2;
if(arr[mid] == target) {
return mid;
}
else if(arr[mid] > target) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
return -1;
}
public static void main(String[] args)
{
PerfectBinarySearch BinarySearch = new PerfectBinarySearch();
int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
assert BinarySearch.binarySearch(array, -1) == -1;
assert BinarySearch.binarySearch(array, 11) == -1;
}
}