package day14;
import java.util.ArrayList;
public class binarysearch {
// 二分查找 前提是数组有序
public static void main(String[] args) {
int [] arr ={23,23,45,777,942};
ArrayList<Integer> b = binaerseacrchmethod(arr, 0, arr.length, 23);
System.out.println(b);
}
/**
*
* @param arr
* @param left 左边的值
* @param right 右边的值
* @param findval 查找的值
*/
public static ArrayList<Integer> binaerseacrchmethod(int [] arr, int left, int right, int findval){
// 当left>right,结束递归
if (left>right){
return new ArrayList<Integer>();
}
int mid=(left+right)/2;
int midval =arr[mid]; //中间值
if (findval>midval){
return binaerseacrchmethod(arr,mid+1,right,findval);
}else if (findval<midval){
return binaerseacrchmethod(arr,left,mid-1,findval);
}else {
// 要向左向右移动判断是否
ArrayList<Integer> list = new ArrayList<Integer>();
int temp =mid-1;
while (true){
if (temp<0||arr[temp]!=findval){
break;
}
list.add(temp);
temp--;
}
list.add(mid);
temp =mid+1;
while (true){
if (temp>arr.length-1||arr[temp]!=findval){
break;
}
list.add(temp);
temp++;
}
return list;
}
}
}
二分查找加强版(数组有相同的数)
最新推荐文章于 2023-04-07 00:26:57 发布