一、循环遍历法
package com.chen.ArrayList;
public class Test04 {
//二分法查找也称折半查找(循环遍历),二分法查找必须数组是有序的才能查找
public static void main(String[] args) {
int[]arr={1,2,3,4,5,6,7,8};
System.out.println(binarySearch(arr,5));
}
//定义查找的方法方便我们调用
public static int binarySearch(int[] arr,int temp){//temp为你要查找的数
int low=0;
int high=arr.length-1;
//index定义返回的数,如果数组中没有你查找的数就返回你设定的数(一般这个数我们设定为负数以免影响返回的结果),
//如果有我们查找的数我们就把我们查找的这个数的位置赋给index
int index=-1;
while(low<=high){
int mid=(low+high)/2;
int guess=arr[mid];
if(guess==temp){
index= mid;
break;
}
if(guess<temp){
low=mid+1;
}
if(guess>temp){
high=mid-1;
}
}
return index;
}
}
二、递归法
package com.chen.ArrayList;
public class Test05 {
//二分查找也称折半查找(递归的方法)
public static void main(String[] args) {
int[]arr={1,2,3,4,5,6,7,8};
System.out.println(binarySearch(arr,2,0,arr.length-1));
}
//定义查找的方法方便我们调用,
// arr数组,temp我们查找的值,low数组第一个元素的位置,high数组最后一个元素的位置
public static int binarySearch(int[] arr,int temp,int low,int high){
if(low>high){
return -1;
}
int mid=(low+high)/2;
int guess=arr[mid];//
if(guess==temp){
return mid;
}
if(guess<temp){
return binarySearch(arr,temp,mid+1,high);
}
if(guess>temp){
return binarySearch(arr,temp,low,mid-1);
}
return mid;
}
}