-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearch
More file actions
51 lines (30 loc) · 987 Bytes
/
binarySearch
File metadata and controls
51 lines (30 loc) · 987 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
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.Arrays;
import static java.util.Arrays.binarySearch;
public class main {
public static void main(String[] args) {
//This is binary search
int[] array=new int[100];
for(int i=0;i<array.length;i++){
array[i]=i+1;
}
// There is inbuilt method
// int index= Arrays.binarySearch(array,75);
int index= binarySearch(array,75);
System.out.println("Target found at : "+index);
}
private static int binarySearch(int[] array,int target){
int low=0;
int high=array.length-1;
while(low<=high){
int middle=low+(high-low)/2;
int value=array[middle];
System.out.println(value);
if(target>value)low=middle+1;
else if(target<value)high=middle-1;
else if(target==value) {
return value;
}
}
return -1;
}
}