public class BinarySearch {
public static void main(String[] args) {
int[] arr = {234,245,77,3,543,67,78,95,378,678,205,753,457,2903,340};
int searchWord = 1150;//要查找的数
System.out.println("普通循环查找"+searchWord+" 用的次数是"+generalLoop(arr, searchWord));
System.out.println("二分法查找"+searchWord+" 用的次数是"+binarySearch(arr, searchWord));
}
//普通循环法,最少需要比较一次,比如查找1,最多需要比较15次,比如8721
static int generalLoop(int[] arr,int searchWord){
int searchCount = 0;
for(int i=0;i<arr.length;i++){
searchCount++;
if(searchWord==arr[i]){
break;
}
}
return searchCount;
}
//二分法查找
static int binarySearch(int[] arr,int searchWord){
Arrays.sort(arr);//先对传进来的数组进行排序
int iIndex = 0;//相当于指针的变量
int iStart = 0;
int iEnd = arr.length-1;
int searchCount = 0; //循环次数的统计
for(int i=0;i<arr.length/2;i++){
searchCount++;
iIndex = (iStart+iEnd)/2;
if(arr[iIndex]<searchWord){
iStart = iIndex;
}else if(arr[iIndex]>searchWord){
iEnd = iIndex;
}else {
break;
}
}
return searchCount;
}
}