【发布时间】:2014-07-06 15:26:14
【问题描述】:
如何在 Delphi 中实现泛型插值搜索?我试过从 Wikipedia。但是它返回错误的结果。
function Search(var A: TArray<Integer>; const Index, Count, Item: Integer): Integer;
var
L, H, M: Integer;
begin
L := Index;
H := Count;
Result := -1;
while (A[L] <= Item) and (A[H] >= Item) do
begin
M := L + ((Item - A[L]) * (H - L)) div (A[H] - A[L]);
if A[M] < Item then
L := M + 1
else if A[M] > Item then
H := M - 1
else
Exit(M);
if A[L] = Item then
Exit(L)
else
Exit(-1);
end;
end;
var
A: TArray<Integer>;
I: Integer;
begin
A := TArray<Integer>.Create(1, 2, 3, 4, 5, 7, 7, 7, 7);
I := Search(A, 0, High(A), 5); // Returns -1;
ReadLn;
end.
【问题讨论】:
-
那么,那段代码有什么问题?
-
我对 Delphi 中的泛型一无所知,但最好的方法可能是包含一个泛型函数参数——假设 Delphi 允许它——它接受
Item、数组和两个索引,并返回插值索引。这将取代M的计算。如果不能使用泛型参数,则必须使用函数指针。 -
@Gene 函数不是通用的。它对整数数组进行操作
-
@user3764855
Index和Count参数是什么意思?它们似乎是不必要的。 -
使用低(A)和高(A)不行吗?
标签: delphi delphi-xe6