public class BinarySearch {
public int binarySearch(int[] BinarySearchArray,int k,int low,int high)
{
int mid=0;
while(low<=high)
{
mid=(low+high)/2;
if(BinarySearchArray[mid]==k)
return mid;
else if(BinarySearchArray[mid]>k)
high=mid-1;
else if(BinarySearchArray[mid]<k)
low=mid+1;
}
return 0;
}
public static void main(String[] args) {
int[] BinarySearchArray=new int[]{1,2,3,4,5,6,7,8,9,10};
BinarySearch binarySearch=new BinarySearch();
int k=binarySearch.binarySearch(BinarySearchArray,11,0,BinarySearchArray.length-1);
if(k==0)
{
System.out.println("数组中没有这个数字");
}
else
{
System.out.println("这个数字的位置是:"+k);
}
}
}
|