Cod sursa(job #2231674)

Utilizator b10nd3Oana Mancu b10nd3 Data 15 august 2018 16:18:23
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include<iostream>
#include<fstream>

using namespace std;

int zero(int a[], int n, int x, int i, int j){
	int mid, where=-1, where2;
	while(i<=j && where==-1){
		mid=i+(j-i)/2;
		if(a[mid]==x) {
		where=mid;
	    where2=zero(a,n,x,mid+1,j);
	    if(where2!=-1) where=where2;
		}
		else if(a[mid]<x) i=mid+1;
		else j=mid-1;
	}
	return where;
}


int one(int a[], int n, int x, int i, int j){
	int mid, where=-1, where2;
	while(i<=j && where==-1){
		mid=i+(j-i)/2;
		if(a[mid]<=x) {
		where=mid;
	    where2=one(a,n,x,mid+1,j);
	    if(where2!=-1) where=where2;
		}
		else j=mid-1;
	}
	return where;
}


int two(int a[], int n, int x, int i, int j){
	int mid, where=-1, where2;
	while(i<=j && where==-1){
		mid=i+(j-i)/2;
		if(a[mid]>=x) {
		where=mid;
	    where2=two(a,n,x,i,mid-1);
	    if(where2!=-1) where=where2;
		}
		else i=mid+1;
	}
	return where;
}


int main(){
	ifstream in("cautbin.in");
	FILE *out=fopen("cautbin.out","w");
	int i, n, m, c, x;
	in>>n;
	int a[n+3];
	for(i=1;i<=n;i++) in>>a[i];
	in>>m;
	while(m--){
		in>>c>>x;
		switch(c){
			case 0: fprintf(out,"%i\n",zero(a,n,x, 1, n));
			        break;
			case 1: fprintf(out,"%i\n",one(a,n,x, 1, n));
			        break;  
			case 2: fprintf(out,"%i\n",two(a,n,x, 1, n));
			        break; 		      
			default: break;
		}
	}
	
	in.close(); fclose(out);
	return 0;
}