package exce;
public class countNum {
public static void main(String[] agrs) throws Exception {
/*int a[]= {1,2,3,4,5,6};
int low=0;
int high=a.length-1;
int value=2;
while(low<=high) {
int mid=low+(high-low)>>2;
if(a[mid]==value) {
System.out.print(mid);
break;
}else if(a[mid]>value) {
high=mid-1;
}else if(a[mid]<value){
low=mid+1;
}
} */
BSForMutation2();
}
//二分查找第一个等于某值得元素
public static void BSFoMutation1() throws Exception {
int a[]= {1,2,2,3,4,5,6};
int low=0;
int high=a.length-1;
int value=2;
while(low<=high) {
int mid=low+((high-low)>>1);
if(a[mid]==value ) {//等于查找值
if(mid==0||a[mid-1]!=value) {//是第一个
System.out.print(mid);
break;
}else { //不是第一个
high=mid-1;
}
}else if(a[mid]>value) {
high=mid-1;
}else if(a[mid]<value){
low=mid+1;
}
}
}
//二分查找最后一个等于某值得元素
public static void BSForMutation2() throws Exception {
//int a[]= {1,2,2,3,4,5,6};
int a[]= {2};
int low=0;
int high=a.length-1;
int value=2;
while(low<=high) {
int mid=low+((high-low)>>1);
if(a[mid]==value ) {//等于查找值
if(mid==0 ||a[mid+1]!=value ) {//是最后一个
System.out.print(mid);
break;
}else{ //不是最后一个
low=mid+1;
}
}else if (a[mid]>value) {
high=mid-1;
}else if(a[mid]<value){
low=mid+1;
}
}
}
//查找第一个大于等于给定值的元素
public static void BSForMutation3() throws Exception {
int a[]= {1,2,2,3,4,5,6};
int low=0;
int high=a.length-1;
int value=2;
while(low<=high) {
int mid=low+((high-low)>>1);
if(a[mid]>=value ) { //在左边区域查找
if(mid==0 || a[mid-1]<value ) {
System.out.print(mid);
break;
}else {
high=mid-1;
}
}else if(a[mid]<value){ //在右边区域查找
high=mid-1;
}
}
}
//查找最后一个小于等于给定值的元素
public static void BSForMutation4() throws Exception {
int a[]= {1,2,2,3,4,5,6};
int low=0;
int high=a.length-1;
int value=2;
while(low<=high) {
int mid=low+((high-low)>>1);
if(a[mid]<=value) {
if(mid==0 || a[mid+1]>value) { //是最后一个小于等于
System.out.print(mid);
break;
}else {//不是最后一个小于等于
low=mid+1;
}
}else if (a[mid]>value) {
high=mid-1;
}
}
}
}