package com.yonyou;
import java.util.*;
public class Demo5 {
public static void main(String[] args) {
int[] arr = new int[]{1, 4, 7, 9, 10, 43, 78, 100, 103, 200, 200, 200, 567};
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
int a = in.nextInt();
List index = binarySearch(arr, 0, arr.length - 1, a);
StringBuilder b = new StringBuilder();
for(int i = 0; i < index.size(); i++){
b.append(index.get(i)+",");
}
System.out.println(b.length() > 0 ? b.toString().substring(0, b.length() - 1) : "");
}
}
private static List<Integer> binarySearch(int[] arr, int low, int high, int target) {
if (low > high) {
return new ArrayList<Integer>();
}
int mid = (low + high) / 2;
if (arr[mid] > target) {
return binarySearch(arr, low, mid - 1, target);
} else if (arr[mid] < target) {
return binarySearch(arr, mid + 1, high, target);
} else {
List<Integer> result = new ArrayList<>();
int left = mid;
int right = mid + 1;
while (left >= 0 && arr[left] == target) {
result.add(left);
left--;
}
while (right < arr.length && arr[right] == target) {
result.add(right);
right++;
}
return result;
}
}
}
数据结构与算法-二分查找法
最新推荐文章于 2024-07-23 21:45:09 发布