编写一个Java应用程序,已知有序整型序列(3,8,9,12,22,23,32,35,45,47,67,89),输入某个值,采用二分查找,查找成功返回所有位置序号,查找不成功返回-1。
时间: 2024-04-29 19:22:17 浏览: 78
以下是Java应用程序的代码实现:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class BinarySearch {
public static void main(String[] args) {
int[] arr = {3,8,9,12,22,23,32,35,45,47,67,89};
Scanner input = new Scanner(System.in);
System.out.print("请输入要查找的值:");
int target = input.nextInt();
int index = binarySearch(arr, target);
if (index == -1) {
System.out.println("查找失败!");
} else {
List<Integer> list = new ArrayList<>();
list.add(index);
int left = index - 1;
while (left >= 0 && arr[left] == target) {
list.add(left);
left--;
}
int right = index + 1;
while (right < arr.length && arr[right] == target) {
list.add(right);
right++;
}
System.out.println("查找成功!位置序号为:" + list.toString());
}
}
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
```
运行结果如下:
```
请输入要查找的值:22
查找成功!位置序号为:[4]
```
如果要查找的值在序列中出现多次,程序会返回所有位置序号。如果要查找的值不在序列中,则返回-1。
阅读全文