Cod sursa(job #1424863)

Utilizator RatkinHHKNica Dan RatkinHHK Data 25 aprilie 2015 16:45:47
Problema Cautare binara Scor 0
Compilator c Status done
Runda Arhiva educationala Marime 1.64 kb
#include <stdio.h>
#include <stdlib.h>

int* Vector,N;

int BinarySearch(int Value);

int main()
{
    int Index;
    int i;
    int Order, Value;
    int M;
    FILE* input;
    FILE* output;
    output = fopen("cautbin.out","w");
    input = fopen("cautbin.in","r");

    fscanf(input,"%d",&N);
    Vector = (int*)malloc((N+2)*sizeof(int));
    for(i=1; i<=N; i++) fscanf(input,"%d", Vector+i);
    Vector[0]=-1;
    Vector[N+1] = 2147483647;

    fscanf(input,"%d",&M);
    for(i=0; i<M; i++){
        fscanf(input,"%d",&Order);
        fscanf(input,"%d",&Value);
        switch(Order){
            case 0:
                Index = BinarySearch(Value);
                while(Vector[Index+1] == Value) Index++;
                fprintf(output,"%d\n",Index);
                break;
            case 1:
                Index = BinarySearch(Value);
                while(Vector[Index+1] <= Value) Index++;
                fprintf(output,"%d\n",Index);
                break;
            case 2:
                Index = BinarySearch(Value);
                while(Vector[Index-1] >= Value) Index--;
                fprintf(output,"%d\n",Index);
                break;
        }
    }

    fclose(output);
    fclose(input);
    return 0;
}

int BinarySearch(int Value)
{
    int Left,Right,Index;
    Left = 1;
    Right = N;

    while(Left < Right - 1)
    {
        Index = Left + (Right-Left)/2;
        if(Vector[Index] < Value) Left = Index;
        else  if(Vector[Index] > Value) Right = Index;
                    else if(Vector[Index] == Value) return Index;
    }

    if(Vector[Left] == Value) return Index;
    if(Vector[Right] == Value) return Index;
    return -1;
}