Cod sursa(job #1989809)

Utilizator b10nd3Oana Mancu b10nd3 Data 8 iunie 2017 23:31:38
Problema Cautare binara Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include<fstream>

using namespace std;

void two( int x, int numbers[],int left, int right, int &where){
    int mid=left+(right-left)/2; 
    if(numbers[mid]>=x) where=mid;
    if(left!=right){
      if((x<=numbers[mid]) && mid-1>=left)  two(x,numbers,left,mid-1,where);
      else if(right>=mid+1 && mid-1>=0)  two(x,numbers,mid+1,right,where); 
    }
}


void one( int x, int n, int numbers[],int left, int right, int &where){
    int mid=left+(right-left)/2;
    if(numbers[mid]<=x) where=mid;
    if(left!=right){
      if(x>=numbers[mid] && mid+1<=right) one(x,n,numbers,mid+1,right,where);
      else if(left<=mid-1 && mid+1<=n-1) one(x,n,numbers,left,mid-1,where);
    }
}


void zero(int x, int n, int numbers[],int left, int right, int &where){
    int mid=left+(right-left)/2;
    if(numbers[mid]==x) where=mid;
    if(left!=right){
      if(x>=numbers[mid] && mid+1<=right) zero(x,n,numbers,mid+1,right,where);
      else if(left<=mid-1 && mid+1<=n-1) zero(x,n,numbers,left,mid-1,where);
    }
}


int main(){
ifstream in("cautbin.in"); ofstream out("cautbin.out");
int n,m,i,c,where;
in>>n;
int numbers[n],x;
for(i=0 ;i<n;i++) in>>numbers[i];
in>>m;
for(i=0;i<m;i++){
   in>>c>>x;
   if(c==0) { where=-2; zero(x,n,numbers,0,n-1,where); out<<where+1<<"\n";}
   if(c==1) { where=-2; one(x,n,numbers,0,n-1,where); out<<where+1<<"\n";}
   if(c==2) { where=-2; two(x,numbers,0,n-1,where); out<<where+1<<"\n";}
}

return 0;
}