[问题描述] 这是一种效率高的查找方法,对一组有序数字进行查找.算法简单,即逐步缩小查找范围.
输入:[KEYBOARD] 输出:[SCREEN]
1 5 8 12 12 13 15 16 17 90 15
1 2 3 4 5 6 7 8 9 10 23
FOUND:7
NOT FOUND.
[问题分析] 由于数据按升序排列,故用折半查找最快捷.
program binsearch;const max=10;
var num:array[1..max] of integer;
i,n:integer;
procedure search(x,a,b:integer);
var mid:integer;
begin
if a=b then
if x=num[a] then writeln('Found:',a) else writeln('Number not found')
else begin
mid:=(a+b) div 2;
if x>num[mid] then search(x,mid,b);
if x<num[mid] then search(x,a,mid);
if x=num[mid] then writeln('Found:',mid);
end;
end;
begin
write('Please input 10 numbers in order:');
for i:=1 to max do read(num[i]);
write('Please input the number to search:');
readln(n);
search(n,1,max);
end.