变量:
left、right、mid、index、value
思路:
比arr[mid]大就往右走;
比arr[mid]小就往左走;
有多个目标值的查询
定义一个temp指针
查找一下mid左面和右面是否有相同的元素,有的话加入到集合当中(循环)
代码:
package 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,1234,1234};
List<Integer> ls = binartSearch(arr, 0, arr.length - 1, 1234);
System.out.print(ls);
}
public static List<Integer> binartSearch(int[] arr, int left, int right, int findValue) {
if(left > right) {
System.out.print("没有找到!");
return null;
}
int mid = (left + right) / 2;
if(arr[mid] > findValue) {
return binartSearch(arr, left, mid - 1, findValue);
}else if(arr[mid] < findValue) {
return binartSearch(arr, mid + 1, right, findValue);
}else {
List<Integer> resIndexList = new ArrayList<Integer>();
int temp = mid-1;
while(true) {
if(temp < 0 || arr[temp] != findValue) {
break;
}
resIndexList.add(temp);
temp--;
}
resIndexList.add(mid);
temp=mid+1;
while(true) {
if(temp > arr.length - 1 || arr[temp] != findValue) {
break;
}
resIndexList.add(temp);
temp++;
}
return resIndexList;
}
}
}