1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| package cn.guizimo.search;
import java.util.ArrayList; import java.util.List;
public class BinarySearch { public static void main(String[] args) { int[] arr = {1, 5, 26, 26, 26, 26, 68, 100, 235, 667, 896, 999}; List<Integer> arrayList = binarySearch(arr, 0, arr.length - 1, 25); if (arrayList.size() == 0) { System.out.println("未找到"); } else { System.out.println("下标集为:" + arrayList); } }
public static List<Integer> binarySearch(int[] arr, int left, int right, int value) { if (left > right) { return new ArrayList<Integer>(); } int mid = (left + right) / 2; int midValue = arr[mid]; if (value > midValue) { return binarySearch(arr, mid + 1, right, value); } else if (value < midValue) { return binarySearch(arr, left, mid - 1, value); } else { List<Integer> resIndexList = new ArrayList<Integer>(); int temp = mid - 1; while (true) { if (temp < 0 || arr[temp] != value) { break; } resIndexList.add(temp); temp -= 1; } resIndexList.add(mid); temp = mid + 1; while (true) { if (temp > arr.length - 1 || arr[temp] != value) { break; } resIndexList.add(temp); temp += 1; } return resIndexList; } }
}
|