-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstAndLastElement.java
More file actions
42 lines (37 loc) · 1 KB
/
FirstAndLastElement.java
File metadata and controls
42 lines (37 loc) · 1 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
import java.util.Arrays;
public class FirstAndLastElement {
public static int firstIndex(int a[], int l, int h, int k) {
int res = -1;
while (l<=h) {
int mid = (l + (h-l)/2);
if(a[mid] == k) {
res = mid;
h = mid-1;
}
else if(a[mid]<k) l = mid+1;
else h = mid-1;
}
return res;
}
public static int lastIndex(int a[], int l, int h, int k) {
int res = -1;
while (l<=h) {
int mid = (l + (h-l)/2);
if(a[mid] == k) {
res = mid;
l = mid+1;
}
else if(a[mid]<k) l = mid+1;
else h = mid-1;
}
return res;
}
public static void main(String args[]) {
int a[] = {};
int k = 0;
int b[] = new int[2];
b[0] = firstIndex(a,0,a.length-1,k);
b[1] = lastIndex(a,0,a.length-1,k);
System.out.println(Arrays.toString(b));
}
}