function BinatySearch(const S: String; StrList : TStringList) : Integer;
implementation
//顺序查找
function SequenceSearch(const S:string; StrList : TStringList) :Integer;
var
i : Integer;
begin
Result := -1;
for i := 0 to StrList.Count - 1 do
if comparetext(S,StrList.Strings[i]) = 0 then
Result := i;
end;
//二分查找
function BinatySearch(const S : String; StrList : TStringList) : Integer;
var
i,Sn,En,Mn : integer;
begin
Result := -1;
Sn := 0;
En := StrList.Count-1;
i := 0;
while Sn <= En do
begin
Mn := (En + Sn)div 2;
if CompareText(S,StrList.Strings[Mn])<0 then begin En := Mn-1;i := i+1; end else
if CompareText(S,StrList.Strings[Mn])>0 then begin Sn := Mn+1;i := i+1; end else
begin
Result := i;
exit;
end;
end;
end;
var
List : TStringList;
i , j : Integer;
begin
List := TStringList.Create;
List.LoadFromFile('test.txt');
i := SequenceSearch('8',List);
Memo1.Lines.Add('顺序查找经过了'+IntToStr(i+1)+'查找');
j := BinatySearch('8',List);
Memo1.Lines.Add('二分经过了'+IntToStr(j+1)+'查找');
end;
procedure TForm1.Button1Click(Sender: TObject);
var
TestList: TStringList;
i: Integer;
n1,n2: Int64;
Count1,Count2: Integer;
s: string;
const
num = 1000000; {准备测试百万个数据}
begin
TestList := TStringList.Create;
for i := 0 to num-1 do TestList.Add(IntToHex(i,8)); {准备有序的测试值列表}
Count1 := 0;
Count2 := 0;
for i := 0 to 9 do
begin
{产生范围内的随机字串}
Randomize;
s := IntToHex(Random(num),8);
QueryPerformanceCounter(n1);
SeqSearch(TestList, s);
QueryPerformanceCounter(n2);
Memo1.Lines.Add(IntToStr(n2-n1)+ #9);
Count1 := Count1 + (n2-n1);
QueryPerformanceCounter(n1);
BinarySearch(TestList, s);
QueryPerformanceCounter(n2);
Memo1.Lines[i] := Memo1.Lines[i] + IntToStr(n2-n1);
Count2 := Count2 + (n2-n1);
end;
Memo1.Lines.Add('平均值:');
Memo1.Lines.Add(IntToStr(Count1 div 10)+ #9 + IntToStr(Count2 div 10));
Memo1.Lines.Add('----------------');
Memo1.Lines.Insert(0, '顺序'#9'二分');
end;