我想在pascal中创建二进制搜索。我一直在努力创建这个代码几个小时,但它仍然没有完成。有人可以帮帮我吗
program binSearch;
uses crt;
TYPE index=1..100;
VAR arr:ARRAY[1..100] OF index;
var lo,hi,search,m,n:integer;
begin
write('n: ');
read(n);
lo:=1;
hi:=n;
while (lo <> hi) do
begin
m:=(lo+hi) DIV 2;
if (arr[m]<search) then
lo:=m+1
else
hi:=m;
end
if (arr[lo]<> search) then
index:=-1
else
index:=lo;
end.
这是我在互联网上找到的内容,但此代码仅告诉您是否找到了用户想要搜索的号码。
PROGRAM binary_search;
USES crt;
TYPE index=1..100;
VAR arr:ARRAY[1..100] OF index;
VAR mid,low,high,search:integer;
i,n:index;
found:boolean;
BEGIN
clrscr;
writeln('Binary search');
writeln('array lengt:');
readln(n);
writeln('Enter ',n,' numbers: ');
FOR i:=1 TO n DO
BEGIN
readln(arr[i]);
END;
writeln('what number do you want to search?');
readln(search);
low:=1;
high:=n;
found:=false;
REPEAT
mid:=trunc(low+high) DIV 2;
IF (search<arr[mid]) THEN
high:=mid-1;
IF (search>arr[mid]) THEN
low:=mid+1;
IF (search=arr[mid]) THEN
found:=true
ELSE
found:=false;
UNTIL ((found=true) OR (high<low));
IF found=true THEN writeln('ELEMENT FOUND')
ELSE writeln('ELEMENT NOT FOUND');
readkey();
END.
答案 0 :(得分:1)
您的代码可以轻松更改以获取找到的元素的索引(请注意,我写了 a而不是,因为搜索值可能有多个元素):您只需插入如果值相同,则比较元素的索引,这另外改善了代码。另一个提示是你应该避免对false/true
的布尔值进行测试:只需使用它们,即在你的代码中使用它们
UNTIL found OR (high<low)
代替UNTIL((found=true) OR (high<low))
。
进一步尝试避免使用high
或low
等预定义名称。这是我对你的代码的调整。如前所述,在查找元素的 索引时存在一些模糊性:如果在5个元素1 2 2 3 4中搜索值2,则程序返回索引3而不是2。
program binary_search;
uses
crt;
type
index=1..100;
var
arr:array[1..100] of index;
var
mid,ilow,ihigh,search:integer;
i,n,fi:index;
found:boolean;
begin
clrscr;
writeln('Binary search');
writeln('array length:');
readln(n);
writeln('Enter ',n,' numbers: ');
for i:=1 to n do begin
readln(arr[i]);
end;
writeln('what number do you want to search?');
readln(search);
ilow :=1;
ihigh :=n;
found :=false;
repeat
mid := (ilow+ihigh) div 2;
if search=arr[mid] then begin
//Element found, record the index in fi and break the search loop
found := true;
fi := mid;
break;
end
else if search<arr[mid] then ihigh := mid-1
else ilow := mid+1;
until ihigh < ilow;
if found then writeln('Element found, Index = ', fi)
else writeln('Element NOT found');
readkey();
end.