二分查找:实现中采用左闭右闭区间。在findPos中,如果要查找的数在数组中有重复值,则返回的是最靠近数组中间位置的值。在findPosFirst中,如果有重复值返回位置最前的值。在findPosLast中,如果有重复值返回位置最后的值。
public class Bsearch
{
public Bsearch(){}
public static int[] array = new int[]{};
public static void search(int t)
{
int res = findPos(t,0,array.length-1);
if(res==-1)
System.out.println("Find the right value:"+"\t"+"Can not find "+t+" in the array!");
else
System.out.println("Find the right value:"+"\t"+t+" is the "+(res+1)+" element in the array!");
res = findPosFirst(t,0,array.length-1);
if(res==-1)
System.out.println("Find the first right value:"+"\t"+"Can not find "+t+" in the array!");
else
System.out.println("Find the first right value:"+"\t"+t+" is the "+(res+1)+" element in the array!");
res = findPosLast(t,0,array.length-1);
if(res==-1)
System.out.println("Find the last right value:"+"\t"+"Can not find "+t+" in the array!");
else
System.out.println("Find the last right value:"+"\t"+t+" is the "+(res+1)+" element in the array!");
}
public static int findPos(int t, int start, int end)
{
if(start>end) return -1;
int l = start;
int h = end;
int mid = (l+h)/2;
if(array[mid]<t)
{
l = mid+1;
return findPos(t,l,h);
}
else if(array[mid]==t)
{
return mid;
}
else
{
h = mid-1;
return findPos(t,l,h);
}
}
public static int findPosFirst(int t, int start, int end)
{
int pos = -1;
int mid;
while(start<=end)
{
mid = (start+end)/2;
if(array[mid]>t) end = mid-1;
else if(array[mid]<t) start = mid+1;
else
{
pos = mid;
end = mid-1;
}
}
return pos;
}
public static int findPosLast(int t, int start, int end)
{
int pos=-1;
int mid;
while(start<=end)
{
mid = (start+end)/2;
if(array[mid]>t) end = mid-1;
else if(array[mid]<t) start = mid+1;
else
{
pos = mid;
start = mid+1;
}
}
return pos;
}
public static void main(String[] args)
{
array = new int[]{1,2,2,2,2};
// array = new int[]{1,2,3,4,5};
int t = 2;
search(t);
}
}