Cod sursa(job #2622214)

Utilizator ihorvaldsTudor Croitoru ihorvalds Data 31 mai 2020 18:09:08
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <iostream>
#include <fstream>

int binary(int* v, int size, int sought, int command) {

    	
    int i, step;
    if (command == 0 || command == 1) {
        for (step = 1; step < size; step <<= 1);
        int prev = step - 1;
        do {
            if (i + step < size && v[i+step] <= sought) {
                i += step;
            }
            prev = i + step;
            step >>=1;
        } while (prev > (step + i));

        if (command == 0 && v[prev] != sought)
            return -1;
        
        if (command == 1 && v[prev] > sought)
            return -1;
        return prev + 1;
    }

    if (command == 2) {
        step = i = 0;
        while (v[step + i] < sought && (i + step) < size) {
            if (step) {
                if ((step << 1 + 1) < size)
                    step <<= 1;
                else
                    i += 1;
            } else {
                step = 1;
            }
        }

        if (i + step == size)
            return -1;

        return (i + step + 1);
    }

    return -1;
}

int main() {
    std::ifstream f("cautbin.in");
    std::ofstream g("cautbin.out");
    int N;
    f >> N;
    int a[1000] = {0};
    for(int i = 0; i < N; ++i) {
        f >> a[i];
    }

    int c;
    int command, s;
    f >> c;
    for(int i = 0; i < c; ++i) {
        f >> command >> s;
        g << binary(a, N, s, command) << "\n";
    }
}