Const n=20; var a:array[1..n] of integer; i,i1,i2,x:integer; begin Randomize; a[1]:=random(10); write(a[1],' '); for i:=2 to n do begin a[i]:=a[i-1]+random(10); write(a[i],' '); end; writeln; write('x = '); readln(x); i1:=1; i2:=n; repeat i:=(i1+i2) div 2; if a[i]<x then i1:=(i1+i2) div 2+1; if a[i]>x then i2:=(i1+i2) div 2-1; until (a[i]=x)or(i1>i2); if a[i]=x then begin writeln('Искомый(ые) номер(а) элемента(ов):'); while (i>0)and(a[i]=x) do i:=i-1; i:=i+1; while (i<=n)and(a[i]=x) do begin write(i,' '); i:=i+1; end; end else writeln('Элемент не найден'); writeln; end.
Answers & Comments
Verified answer
Const n=20;var a:array[1..n] of integer;
i,i1,i2,x:integer;
begin
Randomize;
a[1]:=random(10);
write(a[1],' ');
for i:=2 to n do
begin
a[i]:=a[i-1]+random(10);
write(a[i],' ');
end;
writeln;
write('x = '); readln(x);
i1:=1; i2:=n;
repeat
i:=(i1+i2) div 2;
if a[i]<x then i1:=(i1+i2) div 2+1;
if a[i]>x then i2:=(i1+i2) div 2-1;
until (a[i]=x)or(i1>i2);
if a[i]=x then
begin
writeln('Искомый(ые) номер(а) элемента(ов):');
while (i>0)and(a[i]=x) do i:=i-1;
i:=i+1;
while (i<=n)and(a[i]=x) do begin write(i,' '); i:=i+1; end;
end
else writeln('Элемент не найден');
writeln;
end.
Пример:
5 6 14 15 15 22 30 36 45 45 50 56 60 64 67 76 84 92 99 101
x = 15
Искомый(ые) номер(а) элемента(ов):
4 5