RAD Studio 10.2.3 测试√
这个 Find 是自己仿照加上自己的理解写的
- 仿照来源于:System.Classes 中的 Find
- 有什么不对的地方还希望看到的大佬能够指点一些,感谢
// 使用这个方法的前提是,List中的内容必须是有序的而且还是从小到大,不然只能查找到中间下标的那个值
function Find(const AStr: string; var AIndex: Integer; mList: TStringList): Boolean;
function CompareStrings(const AS1, AS2: string): Integer;
begin
// 中间值和目标的比较
if AS1 > AS2 then
begin
Result := -1;
end
else if AS1 < As2 then
begin
Result := 1;
end
else
begin
Result := 0;
end;
end;
var
// 这三个分别对应源码中的 L, H, I
// 分别对应List中的下标号的最小,最大,中间值
mMin, mMax, mMid: Integer;
// 比较结果
mS: Integer;
begin
Result := False;
// 从 0 号下标开始
mMin := 0;
// 最大的下标为 List 个数减 1
mMax := mList.Count - 1;
while mMin <= mMax do
begin
// 中间的下标 【等同于源码中的(L + H) shr 1】
mMid := (mMin + mMax) div 2;
// 比较中间值和目标值
mS := CompareStrings(mList[mMid], AStr);
if mS > 0 then
begin
// 这个值在中间值和最大值之间
mMin := mMid + 1;
end
else
begin
// 这个值在最小值和中间值之间
mMax := mMid - 1;
if mS = 0 then
begin
// 中间值等于目标值 返回中间值得下标
Result := True;
mMin := mMid;
end;
end;
AIndex := mMin;
end;
end;
procedure TForm1.Button_StringListFindClick(Sender: TObject);
var
mStrList: TStringList;
mIndex, i: Integer;
mStr: string;
begin
mStrList := TStringList.Create;
try
// mStrList.Add('6');
// mStrList.Add('1');
// mStrList.Add('5');
// mStrList.Add('2');
// mStrList.Add('3');
// mStrList.Add('4');
mStrList.Add('1');
mStrList.Add('2');
mStrList.Add('3');
mStrList.Add('4');
mStrList.Add('5');
mStrList.Add('6');
// mStrList.Add('6');
// mStrList.Add('5');
// mStrList.Add('4');
// mStrList.Add('3');
// mStrList.Add('2');
// mStrList.Add('1');
for i := 0 to 6 do
begin
if mStrList.Find(IntToStr(i), mIndex) then
begin
mStr := IntToStr(mIndex);
Memo1.Lines.Add('mStrList.Find: ' + mStr);
end;
if Find(IntToStr(i), mIndex, mStrList) then
begin
mStr := IntToStr(mIndex);
Memo1.Lines.Add('Find: ' + mStr);
end;
end;
finally
mStrList.Free;
end;
end;
可以对照一下 System.Classes 中的 Find
function TStringList.Find(const S: string; var Index: Integer): Boolean;
var
L, H, I, C: Integer;
begin
Result := False;
L := 0;
H := FCount - 1;
while L <= H do
begin
I := (L + H) shr 1;
C := CompareStrings(FList[I].FString, S);
if C < 0 then L := I + 1 else
begin
H := I - 1;
if C = 0 then
begin
Result := True;
if Duplicates <> dupAccept then L := I;
end;
end;
end;
Index := L;
end;
一点点笔记,以便以后翻阅。