首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > .NET >

从A数组中觅B数组中的相近的数字

2012-10-11 
从A数组中找B数组中的相近的数字怎么在一个数字数组中寻找另一个数组中各个数据的位置的a[]{1.2,3.4,4.0,

从A数组中找B数组中的相近的数字
怎么在一个数字数组中寻找另一个数组中各个数据的位置的
a[]={1.2,3.4,4.0,4.4,5.3,6.3,7,7.45,.......,100} n个数,double类型

b[]={4.0,7,...,80} m个数,double类型 m<n 

寻找b数组元素在a数组中的位置或者最相近数的位置

b数组中的数最大不大于a数组中的数,且high(a)<high(b)

[解决办法]
二分法查找。
[解决办法]
原文 "b数组中的数最大不大于a数组中的数,且high(a)<high(b)" 这句话,前后矛盾。以文字定义为准:

Delphi(Pascal) code
unit Unit1;interfaceuses  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  Dialogs, StdCtrls;type  TForm1 = class(TForm)    Button1: TButton;    Memo1: TMemo;    Button2: TButton;    Memo2: TMemo;    Memo3: TMemo;    procedure Button1Click(Sender: TObject);    procedure Button2Click(Sender: TObject);  private    { Private declarations }  public    { Public declarations }  end;var  Form1: TForm1;implementationvar a:array[0..100]of double;    b:array[0..100]of double;{$R *.dfm}//随机产生a、b两组数:procedure TForm1.Button1Click(Sender: TObject);var i,j:integer;    tmp:double;    t:boolean;begin  Randomize;//初始化  for i:=0 to 100 do begin    while true do begin      tmp:=random(100)+random(10)/10;      t:=true;      for j:=0 to i-1 do begin        if a[j]=tmp then begin          t:=false;          break;        end;      end;      if t then begin        a[i]:=tmp;        break;      end;    end;  end;  for i:=0 to 100 do begin    while true do begin      tmp:=random(89)+random(10)/10;      t:=true;      for j:=0 to i-1 do begin        if b[j]=tmp then begin          t:=false;          break;        end;      end;      if t then begin        b[i]:=tmp;        break;      end;    end;  end;  for i:=0 to 100 do begin    memo1.Lines.Append(floattostr(a[i]));    memo2.Lines.Append(floattostr(b[i]));  end;end;//查找b组数在a组最接近的数的位置:procedure TForm1.Button2Click(Sender: TObject);var i,x:integer;    d,f:double;    t:boolean;begin  for i:=0 to 100 do begin    f:=0;    t:=true;    x:=-1;    while true do begin      if t then begin        d:=b[i]+f;        t:=false;      end      else begin        d:=b[i]-f;        f:=f+0.1;        t:=true;      end;      x:=memo1.Lines.IndexOf(floattostr(d));      if x>=0 then break;    end;    memo3.Lines.Append(inttostr(x));//显示在 a 组的位置(0为第一个)  end;end;end.
[解决办法]
如果都排过序了,1楼所言,2分法查找,循环b,2分法在a中找,可以利用上次的搜索结果(序号),就可以不搜索上一次的范围了.

热点排行