问题1:请对一个有序数组进行二分查找{1,8,10,89,1000,1234},输入一个数看看该数组是否存在此数,并且求出下标,如果没有,就提示没有这个数;
问题2:请对一个有序数组进行二分查找{1,8,10,89,1000,1000,1000,1324},输入一个数看看该数组是否存在此数,如果存在,求出所有下标;
补充:二分查找适用的前提是数组是有序的
package com.athome.search;
import java.util.ArrayList;
import java.util.List;
public class BinarySearch {
public static void main(String[] args) {
int[] arr ={1,8,10,89,1000,1324};
int index = binarySearch1(arr,1000);
int index1 = binarySearch2(arr,0, arr.length-1, 1000);
if(index ==-1){
System.out.println("没有找到");
}else {
System.out.println("找到,下标=" +index);
}
int[] arr1 ={1,8,10,89,1000,1000,1000,1324};
List<Integer> resIndexList =binarySearch3(arr1,0,arr.length-1,5000);
System.out.println("resIndexList =" +resIndexList);
}
//非递归的方式二分查找
public static int binarySearch1(int[] arr,int target){
int left =0;
int right = arr.length-1;
int mid;
while (left <=right){
mid = left + (right - left) /2; // 更新中间索引
if(arr[mid] == target){
return mid;
} else if (arr[mid]< target){
left = mid + 1;
}else {
right = mid -1;
}
}
return -1;
}
//递归方式,此方法适用于原有序数组没有相同的元素
public static int binarySearch2(int[] arr,int left,int right,int findVal){
//当left>right,说明递归整个数组,但是没有找打
if(left >right){
return -1;
}
int mid = left + (right - left) /2;
int midVal = arr[mid];
if(findVal > midVal){//向右递归
return binarySearch2(arr,mid+1,right,findVal);
} else if(findVal < midVal){//向左递归
return binarySearch2(arr,left,mid-1,findVal);
}else {
return mid;
}
}
//递归方式,此方法适用于原有序数组有相同的元素,输出所有等于查找值的数组下标
public static List<Integer> binarySearch3(int[] arr, int left, int right, int findVal){
//当left>right,说明递归整个数组,但是没有找打
if(left >right){
return new ArrayList<Integer>();
}
int mid =left + (right - left) /2;;
int midVal = arr[mid];
if(findVal > midVal){//向右递归
return binarySearch3(arr,mid+1,right,findVal);
} else if(findVal < midVal){//向左递归
return binarySearch3(arr,left,mid-1,findVal);
}else {
List<Integer> resultList = new ArrayList<Integer>();
//向mid索引值的左边扫描,将所有满足1000的元素的下标,加入到ArrayList
int temp =mid -1;
while(true){
if(temp<0||arr[temp] != findVal){
break;
}
resultList.add(temp);
temp-=1;
}
resultList.add(mid);
//向mid索引值的右边扫描,将所有满足1000的元素的下标,加入到ArrayList
temp =mid +1;
while(true){
if(temp>arr.length-1||arr[temp] != findVal){
break;
}
resultList.add(temp);
temp+=1;
}
return resultList;
}
}
}