• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

《Delphi算法与数据结构》学习与感悟[1]:通过"顺序查找"与"二分查找&q ...

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
测试效果图:


unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{顺序查找函数}
function SeqSearch(List: TStringList; const str: string): Integer;
var
  i: Integer;
begin
  for i := 0 to List.Count - 1 do
    if CompareText(List[i], str) = 0 then begin Result := i; Exit; end;
  Result := -1;
end;

{二分查找函数; 二分查找只能针对有序列表}
function BinarySearch(List: TStringList; const str: string): Integer;
var
  L,R,M: Integer;
  CompareResult: Integer;
begin
  Result := -1;
  L := 0;
  R := List.Count - 1;

  while L <= R do
  begin
    M := (L + R) div 2;
    CompareResult := CompareText(List[M], str);
    if CompareResult < 0 then L := M + 1 else
    if CompareResult > 0 then R := M - 1 else
    begin
      Result := M;
      Exit;
    end;
  end;
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)); {准备有序的测试值列表}

  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;

end.

二分查找太快了, 用 GetTickCount 测试不出来, 只好使用 QueryPerformanceCounter;
另外 TStringList.Find 方法也是使用了 "二分查找" 的办法.

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
matlab矩阵数乘学习发布时间:2022-07-18
下一篇:
matlab矩阵运算——乘法、除法学习发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap