Busqueda Binaria
pascal:
program busbina;
uses
crt;
type
vector=array [1..10] of integer;
var
v:vector;
encon:boolean;
primero,ultimo,q,central,p:integer;
begin
clrscr;
for q:=1 to 10 do
begin
write(q,' .- ');
readln(v[q])
end;
for q:=1 to 10 do
begin
primero:=q+1;
for primero:=primero to 10 do
begin
if v[primero] < v[q] then
begin
ultimo:= v[primero];
v[primero]:=v[q];
v[q]:=ultimo
end
end
end;
encon:= false;
primero:=1; ultimo:=10;
clrscr;
write('Introduce Elemento a buscar: ');
readln(q);
while (primero <= ultimo) and (encon = false) do {Busqueda }
begin
central:= (primero+ultimo) div 2;
if q = v[central] then
encon:= true
else
if q > v[central] then
primero:=central+1
else
ultimo:=central-1;
end;
if encon = true then
p:=central
else
p:=0;
writeln;
writeln;
writeln;
if p=central then
writeln('Elemento buscado en la posicion ',p)
else
writeln('Elemento no existente ');
readln
end.
uses
crt;
type
vector=array [1..10] of integer;
var
v:vector;
encon:boolean;
primero,ultimo,q,central,p:integer;
begin
clrscr;
for q:=1 to 10 do
begin
write(q,' .- ');
readln(v[q])
end;
for q:=1 to 10 do
begin
primero:=q+1;
for primero:=primero to 10 do
begin
if v[primero] < v[q] then
begin
ultimo:= v[primero];
v[primero]:=v[q];
v[q]:=ultimo
end
end
end;
encon:= false;
primero:=1; ultimo:=10;
clrscr;
write('Introduce Elemento a buscar: ');
readln(q);
while (primero <= ultimo) and (encon = false) do {Busqueda }
begin
central:= (primero+ultimo) div 2;
if q = v[central] then
encon:= true
else
if q > v[central] then
primero:=central+1
else
ultimo:=central-1;
end;
if encon = true then
p:=central
else
p:=0;
writeln;
writeln;
writeln;
if p=central then
writeln('Elemento buscado en la posicion ',p)
else
writeln('Elemento no existente ');
readln
end.