Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
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
Tags
more
Archives
Today
Total
관리 메뉴

main

[백준-1920번/Java] 수 찾기 본문

Algorithm

[백준-1920번/Java] 수 찾기

1984 2022. 11. 11. 12:50

* 이분탐색 (Binary Search)

import java.util.*;
import java.io.*;

public class Main {

	static int BinarySearch(int key, int low, int high, int[] arr) {

		if (low > high)
			return 0;

		int mid = (low + high) / 2;

		if (arr[mid] == key) {
			return 1;
		} else if (arr[mid] > key) {
			return BinarySearch(key, low, mid - 1, arr);
		} else if (arr[mid] < key) {
			return BinarySearch(key, mid + 1, high, arr);
		}

		return 0;
	}

	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();
		int[] arr = new int[N];

		for (int i = 0; i < arr.length; i++) {
			arr[i] = sc.nextInt();
		}

		Arrays.sort(arr);

		int M = sc.nextInt();
		for (int i = 0; i < M; i++) {
			int num = sc.nextInt();
			bw.write(BinarySearch(num, 0, arr.length - 1, arr) + "\n");
		}
		bw.flush();
		sc.close();
	}

}
728x90
Comments