主题:二分查找,修改程序,来!急救!
var
a:array[1..10] of integer;
i,x,l,r,mid:integer;
begin
for i:= 1 to 10 do readln(a[i]);
write('read x ');
readln(x);
l:=1;
r:=10;
while (l<=r) and (x<>a[mid]) do
begin
mid:=(l+r) div 2;
if x=a[mid] then
writeln(x:5,mid:5,' yes')
else
if x<a[mid] then
r:=mid+1
else
l:=mid-1;
end;
if l>r then writeln(x:5,' no');
readln;
end.
var a:array[1..10] of integer;
f,r,x,k:integer;
procedure search(x,top,bot:integer);
var mid:integer;
begin
if top<=bot then
begin
mid:=(top+bot) div 2;
if x=a[mid] then writeln(x:5,mid:5,'yes')
else
if x<a[mid] then search(x,top,mid+1)
else search(x,mid-1,bot)
end
else writeln(x:5,'no');
end;
begin
writeln('input');
for k:=1 to 10 do
read(a[k]);
readln(x);
f:=1;r:=10;
search(x,f,r);
end.
一个是递归,一个是循环,在查找第九号位置的数时会出错,其他好像还好,怎么改?
a:array[1..10] of integer;
i,x,l,r,mid:integer;
begin
for i:= 1 to 10 do readln(a[i]);
write('read x ');
readln(x);
l:=1;
r:=10;
while (l<=r) and (x<>a[mid]) do
begin
mid:=(l+r) div 2;
if x=a[mid] then
writeln(x:5,mid:5,' yes')
else
if x<a[mid] then
r:=mid+1
else
l:=mid-1;
end;
if l>r then writeln(x:5,' no');
readln;
end.
var a:array[1..10] of integer;
f,r,x,k:integer;
procedure search(x,top,bot:integer);
var mid:integer;
begin
if top<=bot then
begin
mid:=(top+bot) div 2;
if x=a[mid] then writeln(x:5,mid:5,'yes')
else
if x<a[mid] then search(x,top,mid+1)
else search(x,mid-1,bot)
end
else writeln(x:5,'no');
end;
begin
writeln('input');
for k:=1 to 10 do
read(a[k]);
readln(x);
f:=1;r:=10;
search(x,f,r);
end.
一个是递归,一个是循环,在查找第九号位置的数时会出错,其他好像还好,怎么改?