cautare binara

Cautare binara

Se citeste un vector cu n componente numere intregi,ordonate crescator si o valoare intreaga x.Sa se decida daca x se gaseste sau nu printre componentele vectorului

#include<iostream.h>
int v[100],n,x;

void caut(int i,int j)
{
if(x==v[(i+j)/2])
cout<<“gasit”<<” “<<“indice “<<(i+j)/2;
else
if(i<j)
if(x<v[(i+j)/2])
caut(i,(i+j)/2 -1);
else caut((i+j)/2+1,j);
else cout<<“nu s-a gasit”;
}

void main()
{
cout<<“n=”;cin>>n;
for(int i=0;i<n;i++)
{
cout<<“v[“<<i<<“]=”;
cin>>v[i];
}
cout<<“numarul cautat:”;cin>>x;
caut(0,n-1);
}

{joscommentenable}

cautare in vector

#include<iostream.h>
#include<conio.h>
typedef int vector[20];
int n;vector v;

int e(int n,int x)
{
if (n==0) return 0;
else
if (v[n]==x) return 1;
else return e(n-1,x);
}

void main()
{
int x,i;
cout<<“n=”;cin>>n;
cout<<“x=”;cin>>x;
for(i=1;i<=n;i++) {cout<<“v[“<<i<<“]=”;cin>>v[i];}
if (e(n,x)) cout<<“este”<<endl;
else cout<<“nu este”;
getch();
}