关于二分法
package com.ahuiby.demo1;
public class BinarySearch {
//二分法
public static int binarySearch(int arr[],int key){
int begin=0;
int end =arr.length-1;
while(begin<=end){
if(arr[(begin+end)/2]<key){
begin=(begin+end)/2+1;
}else if(arr[(begin+end)/2]==key){
return (begin+end)/2;
}else{
end=(begin+end)/2-1;
}
}
return -1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr={1,2,3,4,5,6,7,8,9,10};
int flag=binarySearch(arr,7);
if(flag==-1){
System.out.println("列表中无此数!");
}else{
System.out.println("该数在数组中的下标为:"+flag);
}
}
}