1.前提
2.思路
3.含有相同值的数组,只查询到一个的代码
例如:数组{ 1, 8, 10, 89,999,1000,1001,1234 },查询1000的位置
public class BinarySearch {public static void main(String[] args) {int arr[] = { 1, 8, 10, 89,999,1000,1001,1234 };int resIndex = binarySearch(arr, 0, arr.length - 1, 1000);System.out.println(resIndex);}public static int binarySearch(int[] arr, int left, int right, int findVal){// 当 left > right 时,说明递归整个数组,但是没有找到if (left>right){return -1;}int mid = (left + right) / 2;int midVal = arr[mid];if (findVal > midVal){// 向 右递归return binarySearch(arr,mid+1,right,findVal);}else if (findVal < midVal) { // 向左递归return binarySearch(arr, left, mid - 1, findVal);} else {return mid;}}
运行结果
5//元素1000对应的数组下标为5
4.增强版(查询所有满足条件的元素下标)
如:查询数组 { 1, 8, 10, 89,1000,1000,1000,1234 }中 1000的元素下标
public class BinarySearch {public static void main(String[] args) {int arr[] = { 1, 8, 10, 89,1000,1000,1000,1234 };int resIndex = binarySearch(arr, 0, arr.length - 1, 1000);List<Integer> resIndexList = binarySearch2(arr, 0, arr.length - 1, 1000);System.out.println("resIndexList=" + resIndexList);}public static List<Integer> binarySearch2(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 binarySearch2(arr, mid + 1, right, findVal);} else if (findVal < midVal) { // 向左递归return binarySearch2(arr, left, mid - 1, findVal);} else {// * 思路分析// * 1. 在找到mid 索引值,不要马上返回// * 2. 向mid 索引值的左边扫描,将所有满足 1000, 的元素的下标,加入到集合ArrayList// * 3. 向mid 索引值的右边扫描,将所有满足 1000, 的元素的下标,加入到集合ArrayList// * 4. 将Arraylist返回List<Integer> resindexlist = new ArrayList<Integer>();//向mid 索引值的左边扫描,将所有满足 1000, 的元素的下标,加入到集合ArrayListint temp = mid - 1;while (true) {if (temp < 0 || arr[temp] != findVal) {//退出break;}//否则,就temp 放入到 resIndexlistresindexlist.add(temp);temp -= 1;//temp左移}resindexlist.add(mid);//将第一次找到的值加入列表temp = mid + 1;while (true) {if (temp > arr.length - 1 || arr[temp] != findVal) {//退出break;}//否则,就temp 放入到 resIndexlistresindexlist.add(temp);temp += 1;//temp左移}return resindexlist;}}}
运行结果
resIndexList=[4, 5, 6]
