Cod sursa(job #2378282)

Utilizator ShumaherAdasga Shumaher Data 11 martie 2019 22:16:58
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <iostream>
#include <fstream>

using namespace std;
ifstream in("cautbin.in");
ofstream out("cautbin.out");
int A[100010];
int N, M;
void citire() {

    in >> N;
    for(int i = 1; i <= N; i++)
        in >> A[i];
    in >> M;
}



int bsearch01(int val, int n) {
    int i, step;
    for(step = 1; step < n; step <<= 1);
    for(i = 0; step; step >>= 1)
        if(i + step < n && A[i + step] <= val)
            i += step;
if(A[i]==val)
                 return i;
    return -1;
}

int bsearch2(int val, int n) {
    int i, step;
    for(step = 1; step < n; step <<= 1);
    for(i = 1; step; step >>= 1)
        if(i + step < n && A[i + step] < val)
            i += step;
                 return i + 1;
}

int main() {
    int tip, val;
    citire();
    for(int i = 1; i <= M; i++) {
        in >> tip >> val;
        if (tip == 2)
            out << bsearch2(val, N);
        else
            out << bsearch01(val, N);
        out << '\n';
    }

}