Cod sursa(job #2722874)

Utilizator ddiana.gamesDiana Games ddiana.games Data 13 martie 2021 12:45:56
Problema Cautare binara Scor 0
Compilator java Status done
Runda Arhiva educationala Marime 1.14 kb
import java.io.*;
import java.util.Scanner;

public class Main {
    public static int solution(int type, int x, int[] arr, int n) {
        int pos, step;

        switch (type) {
            case 2:
                for (pos = -1, step = 1 << 20; step > 0; step >>= 1)
                    if (pos + step < n && arr[pos + step] < x)
                        pos += step;

                return pos + 2;
            default:
                for (pos = -1, step = 1 << 20; step > 0; step >>= 1)
                    if (pos + step < n && arr[pos + step] <= x)
                        pos += step;

                return pos + 1;
        }
    }

    public static void main(String[] args) throws FileNotFoundException, IOException {
        Scanner in = new Scanner(new FileReader("cautbin.in"));
        PrintStream out = new PrintStream("cautbin.out");

        int n = in.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; ++i)
            arr[i] = in.nextInt();
        int m = in.nextInt();
        while (m-- > 0)
            out.printf("%d\n", solution(in.nextInt(), in.nextInt(), arr, n));
        in.close();
        out.close();
    }
}