Mega Code Archive

 
Categories / Delphi / Forms
 

How to perform a binary seach on a TListview

Title: How to perform a binary seach on a TListview function ListviewBinarySearch(listview: TListview; const Item: string; var Index: Integer): Boolean; var First, last, pivot, res: Integer; begin Assert(Assigned(listview)); Assert(Length(item) 0); Result := False; Index := 0; if listview.Items.Count = 0 then Exit; First := 0; last := listview.Items.Count - 1; repeat pivot := (First + last) div 2; res := lstrcmp(PChar(item), PChar(listview.Items[pivot].Caption)); if res = 0 then begin { Found the item, return its index and exit. } Index := pivot; Result := True; Break; end { If } else if res 0 then begin { Item is larger than item at pivot } First := pivot + 1; end { If } else begin { Item is smaller than item at pivot } last := pivot - 1; end; until last ; Index := First; end; { ListviewBinarySearch }