基本介绍
代码实现
public static ArrayList<Integer> binarySearch(int[] arr, int left, int right, int value) {
if (left > right) {
return new ArrayList<Integer>();
}
int mid = (left + right) / 2;
if (value > arr[mid]) {
return binarySearch(arr, mid + 1, right, value);
} else if (value < arr[mid]) {
return binarySearch(arr, left, mid - 1, value);
} else {
ArrayList<Integer> resIndexList = new ArrayList<>();
resIndexList.add(mid);
int temp = mid-1;
while (temp >= 0 && arr[temp] == value) {
resIndexList.add(temp);
temp--;
}
temp = mid+1;
while (temp <= arr.length - 1 && arr[temp] == value) {
resIndexList.add(temp);
temp++;
}
return resIndexList;
}
}
|