逐次探索

明解C言語 入門編 > 6. 関数 >

逐次探索

Delphi


program Project1;

{$APPTYPE CONSOLE}

uses
SysUtils;

const
NINSU = 5;
FAILED = -1;

function search(const ary:array of Integer; const key: Integer):Integer;
var
i: Integer;
begin
result := FAILED;

for i := Low(ary) to High(ary) do
begin
if ary[i] = key then
begin
result := i + 1;
exit;
end;
end;
end;

var
ary: array[1..NINSU] of Integer = (83, 55, 777, 499, 20);
key, idx: Integer;
begin
key := 18;
idx := search(ary, key);

if idx = FAILED then
writeln(format('%dは、見つかりませんでした。', [key]))
else
writeln(format('%dは、%d番目にあります。', [key, idx]));

key := 499;
idx := search(ary, key);

if idx = FAILED then
writeln(format('%dは、見つかりませんでした。', [key]))
else
writeln(format('%dは、%d番目にあります。', [key, idx]));
end.

実行結果

S:\>lesson049\project1.exe
18は、見つかりませんでした。
499は、4番目にあります。