Cod sursa(job #1259504)

Utilizator alexandru.ghergutAlexandru-Gabriel Ghergut alexandru.ghergut Data 10 noiembrie 2014 08:55:37
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.82 kb
#include <fstream>

using namespace std;

int binarySearch(int type, int value, int a[], int N);

int main()
{
    int N, M, type, value, i;
    ifstream f("cautbin.in");
    f >> N;
    int a[N];
    for (i = 0; i < N; i++)
        f >> a[i];
    f >> M;

    ofstream g("cautbin.out");
    for (i = 0; i < M; i++)
    {
        f >> type >> value;
        g << binarySearch(type, value, a, N) << " ";
    }
    f.close();
    g.close();

    return 0;
}

int binarySearch(int type, int value, int a[], int N)
{
    int pos = 0, step;
    step = (1 << 20);

    while (step >>= 1)
    {
        if (pos + step < N && a[pos + step] <= value)
            pos += step;
    }

    if (type == 0 && a[pos] != value)
        pos = -1;
    else if (type == 2)
        while (pos >= 0 && a[pos - 1] == value)
            pos--;

    return ++pos;
}