二分法的思想很简单,因为整个数组是有序的,数组默认是递增的。
public class BinarySearch {
public static void main(String[] args) {
int [] nums = {1,2,3,4,5,9,10,11,19,25};
int target = 19;
/** 第一种方法:实例化对象,
BinarySearch test = new BinarySearch();
System.out.println("实例化对象调用:"+search(nums,target));
*/
//第二种方法:直接通过类名.方法名调用,方法为static的时候使用
System.out.println("下标为:"+ BinarySearch.search(nums,target));
}
//非递归查找
public static int search(int[] nums, int target){
int len = nums.length;
int left=0;
int right=len-1;
//目标存在的区间可能在两者之间 注意"="号
while(left<=right){
int mid = (left+(right-left)/2);
if(nums[mid]==target){
return mid;
}
else{
if(nums[mid]>target){
right = mid - 1 ;
}
else{
left = mid +1 ;
}
}
}
return -1;
}
}
public class BinarySearch02 {
public static void main(String[] args) {
int [] nums = {1,2,3,4,5,9,10,11,19,25};
int target = 19;
//递归需要传参数
int left = 0;
int len = nums.length;
int right = len-1;
//直接通过类名.方法名调用,方法为static的时候使用
System.out.println("下标为:"+ BinarySearch02.Digui(nums,left,right,target));
}
//递归查找
public static int Digui(int[] nums, int left, int right, int target) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] > target) {
return Digui(nums, left, mid - 1, target);
} else if (nums[mid] < target) {
return Digui(nums, mid + 1, right, target);
} else {
return mid;
}
}
return -1;
}
}