ZZULIOJ 1152: 二分搜索,Java
题目描述
在有序序列中查找某一元素x。
输入
首先输入一个正整数n(n<=100000),表示该序列有n个整数,然后按从小到大的顺序输入n个整数;
接着是一个正整数m,表示有m次查找;
最后是m个整数,表示m个要查找的整数x。
输出
对于每一次查找,有一行输出。若序列中存在要查找的元素x,则输出元素x在序列中的序号(序号从0开始);若序列中不存在要查找的元素x,则输出"Not found!"。
样例输入 Copy
5
1 3 5 7 9
11
-1
1
2
3
4
5
6
7
8
9
10
样例输出 Copy
Not found!
0
Not found!
1
Not found!
2
Not found!
3
Not found!
4
Not found!
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;public class Main {
static int[] a = new int[100010];public static int Binary_search(int n, int x) {
int l = 0, r = n - 1;while (l <= r) {
int mid = l + r >> 1;if (a[mid] == x) return mid;else if (a[mid] > x) r = mid - 1;else l = mid + 1;}return -1;}public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));int n = sc.nextInt();for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();}int m = sc.nextInt();while (m-- > 0) {
int x = sc.nextInt();int pos = Binary_search(n, x);if (pos == -1) bw.write("Not found!\n");else bw.write(pos + "\n");}bw.close();}
}