List and BinarySearch index not every correct

白昼怎懂夜的黑 提交于 2019-12-24 13:59:57

问题


i have some problem again about list and binarysearch. In general, i have:

type
  TMyArr = array [1..5] of Integer;    

  PMyList = record
    Comb: TMyArr;
    ... // other fields    
  end;
  TMyList = TList<PMyList>;

var 
  MyArr: TMyArr; 
  MyList: TMyList;  
  rMyList: PMyList;

i load value in array MyArr and want find element MyArr (with all values in it) in list TMyList, then i use:

rMyList.Comb := MyArr;
MyList.BinarySearch(rMyList, iIndex3, TDelegatedComparer<PMyList>.Construct(Compare));

with Compare so defined:

function CompareInt(const Left, Right: Integer): Integer;
begin
  if Left < Right then
    Result := -1
  else if Left > Right then
    Result := 1
  else
    Result := 0;
end;

function Compare(const Left, Right: PMyList): Integer;
begin
  Result := CompareInt(Left.Comb[1], Right.Comb[1]);
  if Result = 0  then
    Result := CompareInt(Left.Comb[2], Right.Comb[2]);
  if Result = 0  then
    Result := CompareInt(Left.Comb[3], Right.Comb[3]);
  if Result = 0  then
    Result := CompareInt(Left.Comb[4], Right.Comb[4]);
  if Result = 0  then
    Result := CompareInt(Left.Comb[5], Right.Comb[5]);
end;

Now, my problem is that not every result is correct. In sense that often i have correct index of element and other time i have other index corresponding to other element, in casual. As i can solve it? Where i have mistake?
I want only find index corresponding of MyArr in TMyArr. Thanks again very much.


回答1:


Your Compare function is just fine. If the binary search fails to work correctly then that can only be because the list is not ordered by the order defined by Compare. Call the Sort function on the list once you have finished populating, and before you start searching. When you call Sort, you must make sure that it use your compare function.



来源:https://stackoverflow.com/questions/8368243/list-and-binarysearch-index-not-every-correct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!