-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary search
52 lines (41 loc) · 1.08 KB
/
Binary search
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
52
package gfg;
//Binary search
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--;
}
}
}
class Solution {
int binarysearch(int arr[], int n, int k) {
// code here
int left = 0;
int right = n - 1;
while(left <= right) {
int mid = (right + left) / 2;
if(arr[mid] == k) {
return mid;
}
else if(arr[mid] > k) {
right = mid - 1;
}
else {
left = mid + 1;
}
}
return -1;
}
}