//非递归算法:
public static int binarySearch_NonRec (int []a , int left, int right, int d){ //left,right均为小标
while (left <right ){ // 利用 while循环改变查找的范围,通过改变 left 和right 大小
int mid =(left +right )/2;
if( d== a[ mid]){
return mid ;
} else if (d <a [mid ]){
right= mid-1;
} else {
left= mid+1;
}
}
if( left== right&& d== a[ left]){
return left ;
}
return -1;
}
当数组中有重复元素,要求返回元素第一次出现的位置:
//有重复元素数组,非递归算法,返回查找元素第一次出现的位置
//left,right 均为小标,返回找到数值的位置(下标 +1 )
public static int getFirst( int []a , int d){
int firstId =d ;
if ( firstId==-1) return -1;
int temp =a [firstId ];
while ((firstId >0)&&( temp== a[ firstId-1])){
firstId--;
}
return firstId +1;
}
//left,right均为小标,返回找到数值的下标
public static int binarySearch_NonRec( int []a , int left, int right, int d){
// 同上
}