-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary Search.java
More file actions
49 lines (42 loc) · 1.04 KB
/
Copy pathBinary Search.java
File metadata and controls
49 lines (42 loc) · 1.04 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
//{ Driver Code Starts
// Initial Template for Java
import java.io.*;
import java.util.*;
public class GFG {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while (T > 0) {
int n = sc.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int key = sc.nextInt();
Solution g = new Solution();
System.out.println(g.binarysearch(arr, n, key));
T--;
}
}
}
// } Driver Code Ends
// User function Template for Java
class Solution {
int binarysearch(int arr[], int n, int k) {
// code here
nt low=0,high=n-1;
while(low<=high){
int mid=(low+high)/2;
if(arr[mid]==k){
return mid;
}
else if(k>arr[mid]){
low=mid+1;
}
else{
high=mid-1;
}
}
return -1;
}
}