-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstOccBinary.java
More file actions
42 lines (34 loc) · 884 Bytes
/
FirstOccBinary.java
File metadata and controls
42 lines (34 loc) · 884 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
public class FirstOccBinary {
public static void main(String[] args)
{
int[] arr = {1, 2, 2, 3, 3, 3, 3, 5, 6, 7};
int key = 3;
int ans = search(arr, key);
System.out.println("The index of "+key+" in the array is : "+ans);
}
private static int search(int[] arr, int key)
{
int s = 0;
int e = arr.length-1;
int ans = -1;
int mid = s + (e - s)/2;
while(s <= e)
{
if(key == arr[mid])
{
ans = mid;
e = mid - 1;
}
else if(key < arr[mid])
{
e = mid - 1;
}
else if(key > arr[mid])
{
s = mid + 1;
}
mid = s + (e - s)/2;
}
return ans;
}
}