import java.util.*;
/**
* 二分查找
* 如果有重复的数字则返回该数字在数组中出现的第一次位置
* @author Administrator
*
*/
public class BinarySearch {
public int getPos(int[] A, int n, int val) {
// write code here
int right=n-1;
int left=0;
int index=(int)((right+left)/2);
while(right>=left){
index=(int)((right+left)/2);
if(A[index]==val){
while(index>=0&&A[index]==val){
index--;
}
return index+1;
}
else if(A[index]>val){
right=index-1;
}
else if(A[index]<val){
left=index+1;
}
}
return -1;
}
public int getPosRecursion(int[] A, int begin,int end, int val){
int right=end;
int left=begin;
int index=(int)((right+left)/2);
if(end<begin){
return -1;
}
else if(A[index]==val){
while(index>=0&&A[index]==val){
index--;
}
return index+1;
}
else if(A[index]>val){
return getPosRecursion(A, begin, index-1,val);
}
else{
return getPosRecursion(A, index+1, end,val);
}
}
public static void main(String[] args) {
int a[]={1,3,3,3,3,6,7,8,9};
int b=new BinarySearch().getPos(a, 9, 3);
int c=new BinarySearch().getPosRecursion(a,0,8,3);
System.out.println(b+" "+c);
}
}