1、循环查找
public class BinarySearch {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7};
int index = binarySearch(arr,5);
System.out.println(index);
}
public static int binarySearch(int[] arr,int item){
int low = 0;
int higt = arr.length-1;
int index = -1;
while (low<=higt) {
int mid = (low + higt) / 2;
int guess = arr[mid];
if (guess == item) {
index = mid;
break;
}
if (guess > item) {
higt = mid - 1;
}
if (guess < item) {
low = mid + 1;
}
}
return index;
}
}
2、递归查找
public class BinarySearch02 {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7};
int index = binarySearch(arr,5,0, arr.length-1);
System.out.println(index);
}
public static int binarySearch(int[] arr,int item,int low,int high){
if (low>high){
return -1;
}
int mid = (low+high)/2;
int guess = arr[mid];
if (guess == item){
return mid;
}
else if (guess > item){
return binarySearch(arr,item,low,mid-1);
}
else{
return binarySearch(arr, item, mid+1, high);
}
}
}
实际上:Arrays有方法
Arrays.sort(arr); //排序
Arrays.binarySearch(arr,6); //查找
3、查找一个数的最后出现在第几位
public class lastPosition {
public int lastPosition(int[] nums,int target){
if(nums == null || nums.length == 0){
return -1;
}
int start = 0;
int end = nums.length-1;
while (start+1 < end){ //start 与 end 是前后关系
int mid = start +(start+end)/2;
if(nums[mid] == target){
start = mid; //如果是求第一次出现 则end = start
}else if(nums[mid] < target){
start = mid;
}else {
end = mid;
}
}
if(nums[end] == target){
return end;
}
if(nums[start] == target){
return start;
}
return -1;
}
}
3、如果确定不了数组长度
public int searchBigSortArray(ArrayReader reader,int target){
//搜索target所在的数组长度
int count = 1;
while(reader.get(count -1) < target){
count = count *2;
}
int start = count /2;
int end = count-1;
while (start+1 < end){ //start 与 end 是前后关系
int mid = start +(start-end)/2;
if(nums[mid] == target){
start = mid;
}else if(nums[mid] < target){
start = mid;
}else {
end = mid;
}
}
if(nums[end] == target){
return end;
}
if(nums[start] == target){
return start;
}
return -1;
}
4、寻找坡峰
public class lastPosition {
public int findPeak(int[] arr){
if(arr == null ) return -1;
int start = 0;
int end = arr.length-2;
while (start+1 < end){
int mid = start + (end - start)/2;
if(arr[mid+1] > arr [mid]){ //递增
start = mid;
}else if(arr[mid-1] > arr[mid] ){
end = mid;
}else {
end = mid ;
}
}
if(arr[start] > arr[end]){
return arr[start];
}else {return arr[end];}
}
public static void main(String[] args) {
int arr[] = new int[]{1,2,1,3,4,5,7,6};
lastPosition astPosition = new lastPosition();
astPosition.findPeak(arr);
System.out.println(astPosition.findPeak(arr));
}
}