I have created two binary search methods for returning first and last occurrences respectively.
public static void main(String[] args) {
int a[] ={1,2,2,2,2,2,5,5,6,8,9,10};
System.out.println(5+" first = "+first(a, 5, 0, a.length-1));
System.out.println(5+" last = "+right(a, 5, 0, a.length-1));
System.out.println(1+" first = "+first(a, 1, 0, a.length-1));
System.out.println(1+" last = "+right(a, 1, 0, a.length-1));
System.out.println(2+" first = "+first(a, 2, 0, a.length-1));
System.out.println(2+" last = "+right(a, 2, 0, a.length-1));
System.out.println(10+" first = "+first(a, 10, 0, a.length-1));
System.out.println(10+" last = "+right(a, 10, 0, a.length-1));
System.out.println(8+" first = "+first(a, 8, 0, a.length-1));
System.out.println(8+" last = "+right(a, 8, 0, a.length-1));
System.out.println(11+" first = "+first(a, 11, 0, a.length-1));
System.out.println(11+" last = "+right(a, 11, 0, a.length-1));
}
private static int first(int [] a, int x, int l, int h){
if(l>h){
return -1;
}
int mid = (h-l)/2+l;
if(a[mid] == x && (mid==0 || a[mid-1] != x) ){
return mid;
}else if(a[mid] == x){
return first(a, x, l, mid-1);
}else if(a[mid]>x){
return first(a, x, l, mid-1);
}else{
return first(a, x, mid+1, h);
}
}
private static int right(int [] a, int x, int l, int h){
if(l>h){
return -1;
}
int mid = (h-l)/2+l;
if(a[mid] == x && (mid==a.length-1 || a[mid+1] != x) ){
return mid;
}else if(a[mid] == x){
return right(a, x, mid+1, h);
}else if(a[mid]>x){
return right(a, x, l, mid-1);
}else{
return right(a, x, mid+1, h);
}
}
Output:
1 first = 0
1 last = 0
2 first = 1
2 last = 5
10 first = 11
10 last = 11
8 first = 9
8 last = 9
11 first = -1
11 last = -1