您的位置:首页 > 其它

顺序查找和二分查找

2008-04-01 15:38 169 查看
昨天写了一个顺序查找算法和二分查找算法的程序,不过测试数据很少,还要求手动添加测试数据。效果不是很好。代码如下:
...........
function SequenceSearch(const S :string; StrList : TStringList) :Integer;
function BinatySearch(const S: String; StrList : TStringList) : Integer;
implementation
{$R *.dfm}
//顺序查找
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;
procedure TForm1.Button1Click(Sender: TObject);
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;
end.
今天上网去查,发现了关于测试算法性能的函数,可是也没有弄很明白,它属于Windows API函数。也找到了相关的代码,放进去测试了一下,效果比较明显。代码如下:

{对比测试}
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)); {准备有序的测试值列表}
Memo1.Clear;
Count1 := 0;
Count2 := 0;
{搞 10 实验}
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('平均值:');
Memo1.Lines.Add(IntToStr(Count1 div 10)+ #9 + IntToStr(Count2 div 10));
Memo1.Lines.Add('----------------');
Memo1.Lines.Insert(0, '顺序'#9'二分');
TestList.Free;
end; ‘#整数’,在以前没见过,也没有用过。这次测试了一下,大概是数据之间的间隔,可是间隔并不随着数字的增大线性的变化,我测试了几次,好像就数值为9时间距最大了。有清楚是怎么回事的请告诉我,不胜感激了 !本文出自 “烧赤壁的博客” 博客,请务必保留此出处http://wzcsying.blog.51cto.com/284684/69397
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐